William Duffy

Glasgow Based C# ASP.NET Web Developer

C# boolean to string extension method

One of the most common operations I find myself repeating when programming is writing a boolean value in a human friendly form. Most users, unless geeky and appreciative of the coolness of datatypes, will not be too comfortable with true/false being used in yes/no context.

I’m a BIG believer in developing my own reusable code libraries and frameworks as I work, so I decided to create a reusable ToString() extension method on the boolean type to cater for this scenario, and thought I’d share it…cause that’s the kind of guy I am!

It’s important to note that I put the extension method within the System namespace. This allows the extension to be available anywhere in your application. Also, I use a regular expression in the implementation, so be sure to import the RegularExpressions namespace.

1
2
3
4
5
using System.Text.RegularExpressions;
 
namespace System
{
}

The first requirement is a simple enum that allows programmatic access to the most common conversions. This lets programmers avoid typing string values if possible, reducing spelling mistakes (which is always a good thing when it comes to us programmers). The enum represents the output in camel case with values in the format TrueFalse.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
///<summary>
///Defines a textual boolean value
///</summary>
///<remarks></remarks>
public enum BooleanText
{
    AcceptedDeclined,
    ActiveInactive,
    CheckedUnchecked,
    CorrectIncorrent,
    EnabledDisabled,
    OnOff,
    YesNo
}

Next we create a static class to expose our extension methods.

1
2
3
public static class BooleanExtensions
{
}

The first ToString() extension method accepts a single parameter of type BooleanText. It runs a super simple regular expression to parse the BooleanText value into two seperate true/false values based on the camel case formatting and then makes a call to the second extension method with the results.

1
2
3
4
5
6
7
8
9
10
11
/// <summary>
/// Assesses a boolean value and returns a textual value
/// </summary>
/// <param name="text">The textual value to be returned</param>
/// <returns>A textual representation of the boolean value</returns>
/// <remarks></remarks>
public static string ToString(this bool value, BooleanText text)
{
    MatchCollection matches = Regex.Matches(text.ToString(), "[A-Z][a-z]+");
    return value.ToString(matches[0].Value, matches[1].Value);
}

The second ToString() extension method accepts two parameters of type System.String. This caters for programmers when the common values in BooleanText are not suitable.

1
2
3
4
5
6
7
8
9
10
11
/// <summary>
/// Assesses a boolean value and returns a specified word in respect to true or false
/// </summary>
/// <param name="trueValue">The textual value to be returned if the current boolean is true</param>
/// <param name="falseValue">The textual value to be returned if the current boolean is false</param>
/// <returns>A string representation of the current boolean value</returns>
/// <remarks></remarks>
public static string ToString(this bool value, string trueValue, string falseValue)
{
    return (value) ? trueValue : falseValue;
}

It’s now simply a case of calling ToString() on your boolean value and getting the output you need straight from the type, rather than writing if/else logic into your code.

1
2
bool value = true;
lblValue.Text = value.ToString(BooleanWord.EnabledDisabled);

Categorized as Uncategorized

4 Comments

  1. Your funky little methods never cease to amaze me! Even in my short career in ASP.NET I have found myself endlessly changing boolean values into “User friendly” strings for things such as Enabled and Disabled, Yes and No etc.

    Thanks a load for sharing =]

  2. That’s a real useful method there. Totally simplifies building grids in admin systems specifically. Man where do you come up with these ideas boy! Awesome (and *ahem* borrowed).

  3. lblValue.Text = value ? “Enabled” : “Disabled”;

    That does the same thing. Less code, can be extended to globalisation, terminology, runs a ton faster since it’s not using regex and if the bool is negated the string values can be swapped around.

    my 2 cents…but I like the idea.

  4. Mike Lawton says:

    Awesome… very nicely done!

comment_type == "trackback" || $comment->comment_type == "pingback" || ereg("", $comment->comment_content) || ereg("", $comment->comment_content)) { ?>

Trackbacks & Pingbacks

  1. Gary Devenay

    Your funky little methods never cease to amaze me! Even in my short career in ASP.NET I have found myself endlessly changing boolean values into “User friendly” strings for things such as Enabled and Disabled, Yes and No etc.

    Thanks a load for sharing =]

  2. comment_type == "trackback" || $comment->comment_type == "pingback" || ereg("", $comment->comment_content) || ereg("", $comment->comment_content)) { ?>

    Trackbacks & Pingbacks

    1. Colin Wiseman

      That’s a real useful method there. Totally simplifies building grids in admin systems specifically. Man where do you come up with these ideas boy! Awesome (and *ahem* borrowed).

    2. comment_type == "trackback" || $comment->comment_type == "pingback" || ereg("", $comment->comment_content) || ereg("", $comment->comment_content)) { ?>

      Trackbacks & Pingbacks

      1. darren

        lblValue.Text = value ? “Enabled” : “Disabled”;

        That does the same thing. Less code, can be extended to globalisation, terminology, runs a ton faster since it’s not using regex and if the bool is negated the string values can be swapped around.

        my 2 cents…but I like the idea.

      2. comment_type == "trackback" || $comment->comment_type == "pingback" || ereg("", $comment->comment_content) || ereg("", $comment->comment_content)) { ?>

        Trackbacks & Pingbacks

        1. Mike Lawton

          Awesome… very nicely done!

        Leave a Reply