16

I am outputting the value of a boolean in my ASP.NET MVC Framework view, and would like to have a lower case true or false, rather than the default of True or False.

I understand that I could just do this:

@this.Model.MyBool.ToString().ToLower()

Alternatively, I could create an extension method. But this defeats the purpose of:

@this.Model.MyBool

I have read the post Why does Boolean.ToString output "True" and not "true", but most of the answers are pretty old.

Are there any more modern ways to accomplish this?

rhughes
  • 9,257
  • 11
  • 59
  • 87

4 Answers4

16

If you only want this for one bool variable you should use @Mohamed 's method. Else you can create an extension method (as you already said yourself):

public static class Extensions
{
    public static string ToLowerString(this bool _bool)
    {
        return _bool.ToString().ToLower();
    }
}

Then to use it:

public static void Main()
{
    bool testBoolean = true;
    Console.WriteLine(testBoolean.ToLowerString());
}
Jevgeni Geurtsen
  • 3,133
  • 4
  • 17
  • 35
14

Why don't you try the following

public string MyStringBool
{
    get { return MyBool ? "true" : "false" ; }
}
Mohamed
  • 470
  • 3
  • 14
  • 2
    This is good, and avoids risking implementation details. See Jon Hanna's comment https://stackoverflow.com/q/491334/292060 – goodeye Jun 09 '17 at 03:01
5

You can also do this which feels syntactically cleaner than true.ToString().ToLower() (in my opinion):

Json.Encode(true);

However under the hood this has far more overhead than using the .ToString.ToLower() implementation.

Json.Encode(object value) has much more error handling as it needs to account for the possibility of more complex objects being passed as arguments.

I did a little benchmarking on this to see what the difference actually is, and on my toaster of a dev box:

var sw0 = Stopwatch.StartNew();
sw0.Stop();

var sw1 = Stopwatch.StartNew();
var t1 = System.Web.Helpers.Json.Encode(true);
var e1 = sw1.ElapsedMilliseconds; // returns 6-9

var sw2 = Stopwatch.StartNew();
var t2 = true.ToString().ToLower();
var e2 = sw2.ElapsedMilliseconds; // returns 0

So really the impact isn't huge for a one off.

Zze
  • 18,229
  • 13
  • 85
  • 118
1

Looks like Microsoft recommends the following (incase you need it for XML too):

public static class BoolExtensions
{
     public static string ToLowerString(this bool _bool)
     {
         return _bool.ToString().ToLowerInvariant();
     }
}

[ToString.()] returns the constants "True" or "False". Note that XML is case-sensitive, and that the XML specification recognizes "true" and "false" as the valid set of Boolean values. If the String object returned by the ToString(IFormatProvider) method is to be written to an XML file, its String.ToLowerInvariant method should be called first to convert it to lowercase.

thalacker
  • 2,389
  • 3
  • 23
  • 44