C# Convert any value to a boolean

Problem

Solution

Discussion

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."); } } }

null

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

bool

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

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

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; }

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."); } } }

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.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.Let's start by creating a static class with a static function that we will call later:That we have our function definition let's implement it piecemeal. To start we will check if it isand throw an exception:Next, we can check if the object type is. If it is, simply return that value:Next, if it is an integer, we can return true or false when the result is 1 or 0: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:That completes the function, here is the full class and function: