Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Convert.ToBoolean("0") fail?

Tags:

c#

I know that trying to convert string "0" to boolean will fail, I also know how to fix this, thanks to Jon Skeets answers on other questions.

What I would like to know is WHY does C# not recognize "0" as a valid input for a boolean conversion, surely you could look at it like 0 = false, 1 = true, or even -1 = false and 0 = true, anyways, my logic tells me that it could be a valid input, so is there a very good reason why its not? My bet is old vb6 would be able to recognize the string input "0" as valid.

like image 766
JL. Avatar asked May 17 '10 23:05

JL.


People also ask

What is Convert ToBoolean?

ToBoolean(Object) Converts the value of a specified object to an equivalent Boolean value. ToBoolean(Decimal) Converts the value of the specified decimal number to an equivalent Boolean value.

Is 0 true or 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 Convert string true to Boolean in c#?

OP, you can convert a string to type Boolean by using any of the methods stated below: string sample = "True"; bool myBool = bool. Parse(sample); // Or bool myBool = Convert. ToBoolean(sample);


4 Answers

The simple answer is because that is the way the method is defined. However, in C# 0 does not evaluate to false, so it would be surprising if "0" were to be converted to false using Convert.

like image 179
Lee Avatar answered Sep 21 '22 10:09

Lee


My guess would be that it's because a C programmer coming over to a .NET language might be confused, since in C a straight cast of the character '0' would evaluate to "true", whereas the character '\0' would evaluate to "false".

(This is because the null character actually is byte full of zeroes, and the '0' character is a nonzero ASCII/Unicode/etc isn't.)

like image 33
Dave Markle Avatar answered Sep 20 '22 10:09

Dave Markle


a string with value always will return to true and even an empty string.

like image 31
Martin Ongtangco Avatar answered Sep 21 '22 10:09

Martin Ongtangco


It's pretty straight forward, Convert.ToBoolean(String) calls Boolean.TryParse(). Which only accepts "True" or "False". If you like to widen the options then you can, there are .NET languages that have a more flexible type system. It is well supported by the .NET framework:

 bool b = (bool)Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean("0");

Add a reference to Microsoft.VisualBasic.dll

like image 33
Hans Passant Avatar answered Sep 18 '22 10:09

Hans Passant