Helping you solve those tough coding problems!

C# Convert any value to a boolean C# Convert any value to a boolean

Published on Apr 5, 2019 by Jamie Munro

Problem


You accept a variety of user input that you want to intelligently convert to a valid boolean variable. E.g. string of On = true. No = false.

Solution





The solution will check the type of input. When the input is already a boolean or integer, we can easily convert it to true or false. When it is a string we will create a list of values that will result to either true or false.

Discussion


Let's start by creating a static class with a static function that we will call later:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Common.Helpers
{
    public static class BoolConverter
    {
        public static bool ConvertToBool(object value)
        {
            throw new ArgumentException(value + " is not a valid boolean value.");
        }
    }
}

That we have our function definition let's implement it piecemeal. To start we will check if it is null and throw an exception:

            if (value == null)
                throw new ArgumentException("Must provide a valid boolean value.");

Next, we can check if the object type is bool. If it is, simply return that value:

            if (value is bool)
                return (bool) value;

Next, if it is an integer, we can return true or false when the result is 1 or 0:

            if (value is int)
            {
                var number = (int) value;
                if (number == 1)
                    return true;
                if (number == 0)
                    return false;
            }

Now for the fun part. When the type is a string we will search for that string in our two lists. One list contains strings that equate to true and the second list contains strings that equate to false. Feel free to expand the list to meet your needs:

            if (value is string)
            {
                var text = (string)value;
                var trueValues = new List {"true", "t", "on", "yes", "y", "1"};
                var falseValues = new List { "false", "f", "off", "no", "n", "0" };

                if (trueValues.Any(t => t.Equals(text, StringComparison.OrdinalIgnoreCase)))
                    return true;

                if (falseValues.Any(t => t.Equals(text, StringComparison.OrdinalIgnoreCase)))
                    return false;
            }

That completes the function, here is the full class and function:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Common.Helpers
{
    public static class BoolConverter
    {
        public static bool ConvertToBool(object value)
        {
            if (value == null)
                throw new ArgumentException("Must provide a valid boolean value.");

            if (value is bool)
                return (bool) value;

            if (value is string)
            {
                var text = (string)value;
                var trueValues = new List {"true", "t", "on", "yes", "y", "1"};
                var falseValues = new List { "false", "f", "off", "no", "n", "0" };

                if (trueValues.Any(t => t.Equals(text, StringComparison.OrdinalIgnoreCase)))
                    return true;

                if (falseValues.Any(t => t.Equals(text, StringComparison.OrdinalIgnoreCase)))
                    return false;
            }

            if (value is int)
            {
                var number = (int) value;
                if (number == 1)
                    return true;
                if (number == 0)
                    return false;
            }

            throw new ArgumentException(value + " is not a valid boolean value.");
        }
    }
}

Tags: ASP.NET | c#

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP