65.9K
CodeProject is changing. Read more.
Home

Parsing Strings to Boolean

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2 votes)

Sep 15, 2010

CPOL
viewsIcon

22302

Handy extension method that parses common boolean expressions

public static class StringExtensions
    {
        private static readonly string[] ValidString = 
                       new[] {"true", "t", "1", "yes", "y"};
        public static bool TryConvertToBoolean(this string input)
        {
            try
            {
                if (input == null) return false;
                // Remove whitespace from string and lowercase
                input = input.Trim().ToLower();
                return ValidString.Contains(input);
            }
            catch
            {
                return false;
            }
        }