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)
You get:
System.InvalidCastException - Conversion from string "Yes" to type 'Boolean' is not valid.
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)
You get:
System.InvalidCastException - Conversion from string "Yes" to type 'Boolean' is not valid.
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.
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
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))> _
...
You Can't. But you should use it as
bool result = yourstring.ToLower() == "yes";