Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToBoolean and Boolean.Parse don't accept 0 and 1

Tags:

.net

boolean

Why was it decided that when parsing a boolean, 0/1 are not acceptable?

When parsing any integer type value, it accepts numerical strings to be parsed. (And if .NET can parse the string "One hundred million two hundred and sixty five thousand eight hundred and sixty five" I would be surprised).

What makes booleans special? They are essentially 0 as false, and non-zero as true in my experience...

Is there a bcl method to parse a string like this, and if not, why?

Note: I forgot to specify in a string "0" and "1". Curious though that if already an int it works as I anticipated. Maybe this caused the confusion.

like image 300
Brett Allen Avatar asked Dec 14 '09 21:12

Brett Allen


People also ask

How do you convert 0 and 1 to true and false?

You can multiply the return Boolean values (TRUE or FALSE) by 1, and then the TRUE will change to 1, and FALSE to 0. Assuming the original formula is =B2>C2, you can change it to =(B2>C2)*1. Note: You can also divide original formula by 1 or add 0 to original formula to change the return TRUE to 1 and FALSE to 0.

Is bool parse case insensitive?

The value parameter, optionally preceded or trailed by white space, must contain either TrueString or FalseString; otherwise, an exception is thrown. The comparison is case-insensitive.

Is 0 true or false in C#?

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 .


2 Answers

0 and (not-zero) are not equal to "false" and "true", they're just the representation chosen by C. Other languages use 0 for true and -1 for false, or other schemes entirely. A boolean is not a 0 or a 1, it's a true or a false.

Should it also handle "yes" and "no", "off" and "on", and all of the myriad other things that are analogous to booleans? Where would you draw the line?

like image 112
Aric TenEyck Avatar answered Oct 10 '22 21:10

Aric TenEyck


What makes booleans special? They are essentially 0 as false, and non-zero as true in my experience...

That is an implementation detail, and isn't at all relevant.

true is a boolean value. false is a boolean value. Anything else is not.

If you want to parse something such that the string "0" evaluates false while anything else evaluates true, you can use:

!mystr.Equals("0"); 
like image 24
Anon. Avatar answered Oct 10 '22 22:10

Anon.