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

Tagged as

Go to top

Parsing Strings to Boolean

, 15 Sep 2010
Rate this:
Please Sign up or sign in to vote.
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;
            }
        }

License

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

Share

About the Author

Enrique Albert
Software Developer (Senior)
Ireland Ireland
No Biography provided
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 3 Pinmember 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 3 PinmemberEnrique Albert2-Feb-13 5:48 
GeneralI don't really like your method. It implies that if the stri... PinmemberSimon Dufour16-Sep-10 4:24 
GeneralRe: I don't really like your method. It implies that if the stri... PinmemberEnrique Albert2-Feb-13 5:50 
GeneralOn the way to a coding horror Pinmemberbhiller20-Sep-10 20:56 
GeneralRe: On the way to a coding horror PinmemberEnrique Albert20-Sep-10 21:43 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 15 Sep 2010
Article Copyright 2010 by Enrique Albert
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid