Click here to Skip to main content
Click here to Skip to main content

Parsing Strings to Boolean

By , 15 Sep 2010
 
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)

About the Author

Enrique Albert
Software Developer (Senior)
Ireland Ireland
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 3member ProgramFOX1 Feb '13 - 6:47 
GeneralRe: My vote of 3memberEnrique Albert2 Feb '13 - 5:48 
GeneralI don't really like your method. It implies that if the stri...memberSimon Dufour16 Sep '10 - 4:24 
I don't really like your method. It implies that if the string isn't in array, it's false.
GeneralRe: I don't really like your method. It implies that if the stri...memberEnrique Albert2 Feb '13 - 5:50 
GeneralOn the way to a coding horrormemberbhiller20 Sep '10 - 20:56 
GeneralRe: On the way to a coding horrormemberEnrique Albert20 Sep '10 - 21:43 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 15 Sep 2010
Article Copyright 2010 by Enrique Albert
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid