Home > Back-end >  C#: string interpolation with boolean formatting
C#: string interpolation with boolean formatting

Time:02-24

How can I specify a format string for a boolean that's consistent with the other format strings for other types?

Given the following code:

double d = Math.PI;
DateTime now = DateTime.Now;
bool isPartyTime = true;

string result = $"{d:0.0}, {now:HH:mm}, time to party? {isPartyTime}";

I can specify a format for every primitive type, except for bool it seems. I know I can do:

string result = $"{d:0.0}, {now:HH:mm}, time to party? {(isPartyTime ? "yes!" : "no")}";

However this is still inconsistent with the other types.

Is there a way of formatting booleans in interpolated strings that is consistent?

P.S. I did search for an answer including this link:

https://stackoverflow.com/questions/tagged/c# string-interpolation boolean

And surprisingly had zero results.

CodePudding user response:

Unfortunately, no, there isn't.

According to Microsoft, the only data types with format strings are:

  • Date and time types (DateTime, DateTimeOffset)
  • Enumeration types (all types derived from System.Enum)
  • Numeric types (BigInteger, Byte, Decimal, Double, Int16, Int32, Int64, SByte, Single, UInt16, UInt32, UInt64)
  • Guid
  • TimeSpan

Boolean.ToString() can only return "True" or "False". It even says, if you need to write it to XML, you need to manually perform ToLowerCase() (from the lack of string formatting).

CodePudding user response:

This may be obvious but to cut down the repetition, you could always create an extension method. It gets you half way there at least.

public static class MyExtensions
{
    public static string ToYesNo(this bool boolValue)
    {
        return boolValue ? "Yes" : "No";
    }
}

static void Main(string[] args)
{
    var booleanValue = true;

    Console.WriteLine(booleanValue.ToYesNo());
}
  • Related