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: Truebool success = bool.TryParse("False", out bool result); // success: Truebool success = bool.TryParse(null, out bool result); // success: Falsebool 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); // Truebool 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();
If you just don't care about what to do when it fails, use this extension:
public static bool GetBool(this string input){var boolResult = false;bool.TryParse(input, out boolResult);return boolResult;}
If it isn't True, true, it is false. No exceptions.