Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can .NET convert "Yes" & "No" to boolean without If?

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.

like image 675
hawbsl Avatar asked May 20 '10 10:05

hawbsl


People also ask

How do you convert boolean to yes or no?

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 ?

Is 0 false in c#?

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 .

How to get bool value in c#?

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.


3 Answers

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.

like image 143
slugster Avatar answered Oct 21 '22 10:10

slugster


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
like image 30
Rubys Avatar answered Oct 21 '22 09:10

Rubys


No, but you could do something like:

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

like image 19
thelost Avatar answered Oct 21 '22 11:10

thelost