C# offers several ways to convert a string value to a boolean value. I will proceed to explain some of them below:
bool.Parse(string value)
or System.Convert.ToBoolean(string value)
Both methods are quite similar in that they both take a string as their input value and return the boolean representation of that string as their output value. Note that both will throw a FormatException
if the input string does not represent a boolean, whereas if the input string is null
, bool.Parse
will throw an ArgumentNullException
while System.Convert.ToBoolean
just returns false
.
// Valid, also TRUE, FALSE, true, false, trUE, FAlse, etc. (case insensitive)
bool result = bool.Parse("True");
bool result = System.Convert.ToBoolean("False");
// Invalid
bool result = bool.Parse(null);
bool result = System.Convert.ToBoolean("thisIsNotABoolean");
bool.TryParse(string value, out bool result)
Similar to bool.Parse
except that it doesn't throw any exceptions directly, instead it returns a boolean value indicating whether or not the conversion could be performed. Also, the converted value now appears in an out bool result
output parameter instead of being returned by the function.
bool success = bool.TryParse("True", out bool result); // success: True
bool success = bool.TryParse("False", out bool result); // success: True
bool success = bool.TryParse(null, out bool result); // success: False
bool success = bool.TryParse("thisIsNotABoolean", out bool result); // success: False
string.Equals(string value)
This is not exactly a direct conversion method and I personally prefer any of the above, but if for some reason you don't have access to them, you can use this alternative.
bool result = "True" .Equals("true", StringComparison.OrdinalIgnoreCase); // True
bool result = "False".Equals("true", StringComparison.OrdinalIgnoreCase); // False
StringExtensions
Depending on what you want to achieve, an extension method might be a good option.
public static class StringExtensions
{
public static bool ToBoolean(this string value)
{
if (bool.TryParse(value, out bool result))
{
return result;
}
return false;
}
}
Then
bool result = "True".ToBoolean();
var result = Convert.ToBoolean("mystring")