Click here to Skip to main content
15,879,096 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 21K   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.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Thomas Daniels1-Feb-13 6:47
mentorThomas Daniels1-Feb-13 6:47 
Your conversion is limited to the strings in your array. If your array doesn't contain the input, but if the input is an equivalent of true, then your method returns false.
GeneralRe: My vote of 3 Pin
Enrique Albert2-Feb-13 5:48
Enrique Albert2-Feb-13 5:48 
GeneralI don't really like your method. It implies that if the stri... Pin
Simon Dufour16-Sep-10 4:24
Simon Dufour16-Sep-10 4:24 
GeneralRe: I don't really like your method. It implies that if the stri... Pin
Enrique Albert2-Feb-13 5:50
Enrique Albert2-Feb-13 5:50 
GeneralOn the way to a coding horror Pin
Bernhard Hiller20-Sep-10 20:56
Bernhard Hiller20-Sep-10 20:56 
GeneralRe: On the way to a coding horror Pin
Enrique Albert20-Sep-10 21:43
Enrique Albert20-Sep-10 21:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.