Click here to Skip to main content
15,919,422 members
Articles / Programming Languages / C#

Parsing Strings to Boolean

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
15 Sep 2010CPOL 21.5K   1   6
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)
                if (input == null) return false;
                // Remove whitespace from string and lowercase
                input = input.Trim().ToLower();
                return ValidString.Contains(input);
                return false;


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 
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 
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... 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.