Parsing Strings to Boolean





4.00/5 (2 votes)
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;
}
}