If you don't need to check for other strings than
True
or
False
, then, you should use
Boolean.Parse
or
Boolean.TryParse
.
Boolean.Parse("true");
Boolean.Parse("false");
Boolean.Parse("foo");
bool isBool;
if(Boolean.TryParse("true", out isBool))
{
}
bool isBool2;
if(Boolean.TryParse("foo", out isBool2))
{
}
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)
{
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.
I have a three years technical education in computer science (June 2006) and a four years bachelor's degree in Software Engineering from the École de Technologie Supérieure (August 2010). I worked as a Web Developper at the beginning of my career before being recruited as a .NET Analyst-Programer at SNC-Lavalin in Montreal. I worked there until they outsourced all development to CGI. I worked there since.