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

 
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 
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 3memberEnrique Albert2 Feb '13 - 5:48 
Maybe you prefer Simon's solution which indicates whether or not the input string was found in the collection:
Parsing Strings to Boolean[^]
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 
I understand your point and I see how you addressed it in your solution. It is a good enhancement.
 
Thanks
GeneralOn the way to a coding horrormemberbhiller20 Sep '10 - 20:56 
Congratulation! Somewhen in the future, somebody maintaining that application will experience a horror similiar to http://www.codeproject.com/Feature/CodingHorrors.aspx?msg=3432553#xx3432553xx[^]. Smile | :)
GeneralRe: On the way to a coding horrormemberEnrique Albert20 Sep '10 - 21:43 
I agree that is a valid point. I propose to define the strings in some sort of resource repository so location can be applied.
 
Thanks

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

Permalink | Advertise | Privacy | Mobile
Web01 | 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