views:

380

answers:

6

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.

A: 

No, but you could do like:

bool yes = "Yes".equals(yourString);

thelost
+15  A: 

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.

slugster
+1 for the wife and the rest
Jehof
+1 for the wife comment
Ardman
You mean we are missing an Important datatype WifeBoolean :)
Mubashar Ahmad
I just let my wife see this answer - she laughed and said it was "Yes".
slugster
WifeBoolean would be a ternary operator, not a boolean...
Paddy
Nah, it is an enum.
Hans Passant
+1  A: 
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
sshow
Be careful of the casing of your input. Maybe use `return (condition.ToUpper() == "YES" ) ? true : false;` instead
ZombieSheep
You're right! +1
sshow
Add more boolean Zen to your code: return condition.ToLower() == "yes"
bniwredyc
+1 on the extension method - nice
stupid-phil
+9  A: 

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
Rubys
If you want it culturally portable, you can also just have a dictionary with some values, so that you can set it in runtime.
Rubys
A: 

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))> _...

Regent
A: 

You Can't. But you should use it as

bool result = yourstring.ToLower() == "yes";
Mubashar Ahmad