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.
To convert a boolean value to Yes/No, use a ternary operator and conditionally check if the boolean value is equal to true , if it is, return yes , otherwise return no , e.g. bool === true ?
Work with Booleans as binary values The C# example must be compiled with the /unsafe switch. The byte's low-order bit is used to represent its value. A value of 1 represents true ; a value of 0 represents false .
Syntax: public bool Equals (bool obj); Here, obj is a boolean value to compare to this instance. Return Value: This method returns true if obj has the same value as this instance otherwise it returns false.
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
No, but you could do something like:
bool yes = "Yes".Equals(yourString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With