Click here to Skip to main content
16,022,924 members
Articles / Programming Languages / C#
Tip/Trick

Parsing Strings to Boolean

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
15 Sep 2010CPOL 22.1K   1   6
Handy extension method that parses common boolean expressions
C#
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;
            }
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Ireland Ireland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.