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.
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.
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 .
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);
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.
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.)
a string with value always will return to true and even an empty string.
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
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