Parsing Strings to Boolean





5.00/5 (5 votes)
If you don't need to check for other strings than True or False, then, you should use Boolean.Parse or Boolean.TryParse.// Return trueBoolean.Parse("true");// Return falseBoolean.Parse("false");// Exception.. you can prevent that from happening by using a try..catch// or using...
If you don't need to check for other strings than
True
or False
, then, you should use Boolean.Parse
or Boolean.TryParse
.
// Return true
Boolean.Parse("true");
// Return false
Boolean.Parse("false");
// Exception.. you can prevent that from happening by using a try..catch
// or using TryParse.
Boolean.Parse("foo");
bool isBool;
if(Boolean.TryParse("true", out isBool))
{
// If we get in here, we know that isBool is a valid boolean,
// either "True" or "False".
}
bool isBool2;
if(Boolean.TryParse("foo", out isBool2))
{
//We won't get in here because "foo" isn't a boolean.
}
Otherwise, I'd use this modified version of TryParse
. If the result isn't True
, or False
, the method will return False
. If the result is found, the method will return True
. The result can be found in the out parameter.
private static readonly List<string> TrueString = new List<string>(new string[]{"true", "t", "1", "yes", "y"});
private static readonly List<string> FalseString = new List<string>(new string[]{"false", "f", "0", "no", "n"});
public static bool TryConvertToBoolean(string input, out bool result)
{
// Remove whitespace from string and lowercase
string formattedInput = input.Trim().ToLower();
if(TrueString.Contains(formattedInput))
{
result = true;
return true;
}
else if (FalseString.Contains(formattedInput))
{
result = false;
return true;
}
else
{
result = false;
return false;
}
}
*UPDATE* The code now compile. Sorry, I hadn't tested.