c# relaxed boolean cast
/// <summary>
/// Parse strings into true or false bools using relaxed parsing rules
/// </summary>
public static class BoolParser
{
/// <summary>
/// Get the boolean value for this string
/// </summary>
public static bool GetValue(string value, bool defaultValue)
{
var result = IsTrue(value, defaultValue);
if (result == null) return defaultValue;
return (bool) result;
}
public static bool? GetValue(string value)
{
return IsTrue(value);
}
/// <summary>
/// Determine whether the string is equal to True
/// </summary>
private static bool? IsTrue(string value, bool? defaultValue = null)
{
try
{
if (value == null)
{
return defaultValue;
}
value = value.Trim().ToLower();
switch (value)
{
case "true":
case "t":
case "1":
case "yes":
case "yeah":
case "yup":
case "y":
return true;
case "false":
case "f":
case "0":
case "no":
case "nope":
case "n":
return false;
default:
return defaultValue;
}
}
catch
{
return defaultValue;
}
}
}