1300 894 506

Bool Format Provider

A non-localised solution to formatting Booleans to “Yes” or “No”

I did a quick bit of research a while ago into how .Net converts a Boolean value to a string (via System.Bool.ToString). It does not make use of the current culture format provider so as such there is no way to easily tap in and override this methods behaviour.

See this reflected code from System.Boolean.ToString:

public override string ToString()
{
    if (!this)
    {
        return "False";
    }
    return "True";
}

Appendix 1

A common scenario is when a developer needs to display the value of a Boolean item inside your aspx/ascx code possibly from within a repeater. Like so:

<%# (bool)Eval(Container.DataItem, "IsActive") ? "Yes" : "No" %>

Appendix 2

A VB.Net approach would probably use the IF ternary operator. There a number of different ways to solve this. You could have a utility function that accepts Booleans (or even objects and attempt to cast them to bool) and call that from your code. However, I wanted a solution that I could easier easily make c easily make accessible from my entire application. I also wanted to be able to extend the behaviour of the conversion. I may want “Yes” or “No” most of the time but sometimes I may want old fashioned “True”/”False” or even something more obscure like “On”/”Off”, “Active”/”Inactive” etc.

So, after a bit of looking around I decided that creating my own implementation of IFormatProvider would be the best approach to take. Coupled with the extension method I could make a new System.Bool.ToString method that would format Booleans how I wanted.
To begin with I created my new BoolFormatProvider:

public class BoolFormatProvider : IFormatProvider, ICustomFormatter
{
    #region ICustomFormatter Members

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        bool value = (bool)arg;
        format = (format == null ? null : format.Trim().ToLower());

        switch (format)
        {
            case "yn":
                return value ? "Yes" : "No";
            default:
                if (arg is IFormattable)
                    return ((IFormattable)arg).ToString(format, formatProvider);
                else
                    return arg.ToString();
        }
    }

    #endregion

    #region IFormatProvider Members

    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    #endregion
}

Appendix 3

So, in BoolFormatProvider I have a switch statement that identifies all the format strings I want to provide for. In this case I have only implemented a single format string for “Yes” & “No” conversions. In the event that an unrecognised format string is provided the default ToString implementation for the value is used.
To use the IFormatProvider only a few methods accept one to format the value. I don’t want a solution that has me manually instantiating a BoolFormatProvider every time I want to use it. So,with the help of an extension method:

namespace MyExtensions
{
    public static class BooleanExtensions
    {
        public static string ToString(this bool value, string format)
        {
            return string.Format(new BoolFormatProvider(), "{0:" + format + "}", value);
        }
    }
}

Appendix 4

With this method created any code that is referencing the MyExtensions namespace can also call this method of an instance of System.Boolean. For use in aspx/ascx pages you can globally include a namespace via the web.config.

<namespaces>
<add namespace=”MyExtensions”/>
</namespaces>

Appendix 5

This should be placed under system.web/pages/. You can now use this from any aspx/ascx page in your website like this:

<%= Convert.ToBoolean("false").ToString("YN") %>

Or

<%# ((bool)Eval(Container.DataItem, "IsActive").ToString("YN") %>

Which makes boolean conversions to Yes/No or any other text representative of a boolean state very easy to implement all across your site from code or aspx/ascx alike.