This method parses a string to see if it matches an equivalent of yes. It tests for strings that should evaluate to true, and if none matches, it considers the default false.
using System;
class Program
{
static void Main()
{
Console.WriteLine(BoolParser.GetValue(
"true"));
// True
Console.WriteLine(BoolParser.GetValue(
"okay"));
// False
Console.WriteLine(BoolParser.GetValue(
"T"));
// True
Console.WriteLine(BoolParser.GetValue(
"False"));
// False
Console.WriteLine(BoolParser.GetValue(
"No"));
// False
Console.WriteLine(BoolParser.GetValue(
"maybe"));
// False
Console.WriteLine(BoolParser.GetValue(
"YES"));
// True
Console.WriteLine(BoolParser.GetValue(
"TRUE "));
// True
Console.WriteLine(BoolParser.GetValue(
"f"));
// False
Console.WriteLine(BoolParser.GetValue(
"1"));
// True
Console.WriteLine(BoolParser.GetValue(
"0"));
// False
Console.WriteLine(BoolParser.GetValue(bool.TrueString));
// True
Console.WriteLine(BoolParser.GetValue(bool.FalseString));
// False
}
}
/// <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)
{
return IsTrue(value);
}
/// <summary>
/// Determine whether the string is not True
/// </summary>
public static bool IsFalse(string value)
{
return !IsTrue(value);
}
/// <summary>
/// Determine whether the string is equal to True
/// </summary>
public static bool IsTrue(string value)
{
try
{
// 1
// Avoid exceptions
if (value == null)
{
return false;
}
// 2
// Remove whitespace from string
value = value.Trim();
// 3
// Lowercase the string
value = value.ToLower();
// 4
// Check for word true
if (value ==
"true")
{
return true;
}
// 5
// Check for letter true
if (value ==
"t")
{
return true;
}
// 6
// Check for one
if (value ==
"1")
{
return true;
}
// 7
// Check for word yes
if (value ==
"yes")
{
return true;
}
// 8
// Check for letter yes
if (value ==
"y")
{
return true;
}
// 9
// It is false
return false;
}
catch
{
return false;
}
}
}
True
False
True
False
False
False
True
True
False
True
False
True
False
String input: true
Bool result: True
String input: false
Bool result: False
String input: t
Bool result: True
String input: f
Bool result: False
String input: yes
Bool result: True
String input: no
Bool result: False
String input: 1
Bool result: True
String input: 0
Bool result: False
String input: Is invalid
Bool result: False