You would think there would be a way using DirectCast, TryCast, CType etc but all of them seem to choke on it e.g.:
CType(\"Yes\", Boolean)
private static bool GetBool(string condition)
{
return condition.ToLower() == "yes";
}
GetBool("Yes"); // true
GetBool("No"); // false
Or another approach using extension methods
public static bool ToBoolean(this string str)
{
return str.ToLower() == "yes";
}
bool answer = "Yes".ToBoolean(); // true
bool answer = "AnythingOtherThanYes".ToBoolean(); // false
C# 6+ version:
public static bool StringToBool(string value) =>
value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) ||
value.Equals(bool.TrueString, StringComparison.CurrentCultureIgnoreCase) ||
value.Equals("1");`
If you think about it, "yes" cannot be converted to bool because it is a language and context specific string.
"Yes" is not synonymous with true (especially when your wife says it...!). For things like that you need to convert it yourself; "yes" means "true", "mmmm yeeessss" means "half true, half false, maybe", etc.
Using this way, you can define conversions from any string you like, to the boolean value you need. 1 is true, 0 is false, obviously.
Benefits: Easily modified. You can add new aliases or remove them very easily.
Cons: Will probably take longer than a simple if. (But if you have multiple alises, it will get hairy)
enum BooleanAliases { Yes = 1, Aye = 1, Cool = 1, Naw = 0, No = 0 } static bool FromString(string str) { return Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), str)); } // FromString("Yes") = true // FromString("No") = false // FromString("Cool") = true
Slightly off topic, but I needed once for one of my classes to display 'Yes/No' instead of 'True/False' in a property grid, so I've implemented YesNoBooleanConverter
derived from BooleanConverter and decorating my property with <TypeConverter(GetType(YesNoBooleanConverter))> _
...
I like the answer that @thelost posted, but I'm reading values from an ADO.Net DataTable and the casing of the string in the DataTable can vary.
The value I need to get as a boolean is in a DataTable named childAccounts
in a column named Trades
.
I implemented a solution like this:
bool tradeFlag = childAccounts["Trade"].ToString().Equals("yes", StringComparison.InvariantCultureIgnoreCase);