Why is Convert.ToBoolean ("0") not working?

I know that an attempt to convert the string "0" to boolean will fail, I also know how to fix it, thanks to John Skets answers on other questions.

What I would like to know is WHY C # does not recognize β€œ0” as a valid input for a logical conversion, of course, you can look at it as 0 = false, 1 = true or even -1 = false and 0 = true in any case, my logic tells me that this can be a valid input, so is there a good reason why it is not? My old vb6 bet will be able to recognize the string input "0" as valid.

+6
c #
source share
7 answers

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

+8
source share

a string with a value always returns true and even an empty string.

+2
source share

I assume that this is because the C programmer switching to the .NET language can be confused, since in C the direct leaflet of the character "0" will be evaluated as "true", while the character "\ 0" will be evaluated as false.

(This is because the null character is actually a byte full of zeros, and the character "0" is non-zero ASCII / Unicode / etc.)

+2
source share

This is pretty straight forward, Convert.ToBoolean (String) calls Boolean.TryParse (). Which accepts only "Truth" or "False." If you want to expand the parameters, then you can, there are .NET languages ​​that have a more flexible type system. This is well supported by the .NET platform:

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

Add link to Microsoft.VisualBasic.dll

+2
source share

For the same reason that the following code will not compile.

 bool value = 0; //error CS0031: Constant value '0' cannot be converted to a 'bool' 
+1
source share

http://msdn.microsoft.com/en-us/library/86hw82a3.aspx
According to the msdn link above, this method Converts the specified string representation of a boolean value to its Boolean equivalent.

 public static bool ToBoolean( string value ) 

Options

value Type: System.String A string containing the value Boolean.TrueString or Boolean.FalseString . Return value

Type: System.Boolean true if the value is TrueString, or false if the value is FalseString or null. Exceptions

0
source share

Whenever you give "0" as a parameter, it considers this a string value. And the string cannot be converted to bool, it doesn't matter if it is 0 or 1 .

0
source share

All Articles