开发者

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

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 v开发者_Go百科alid.


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


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

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


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

public static bool ToBoolean(
    string value
)

Parameters

value Type: System.String A string that contains the value of either Boolean.TrueString or Boolean.FalseString. Return Value

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


Whenever you give "0" as a parameter it considers that as a string value. And string can't be converted to bool doesn't matter whether it is 0 or 1 .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜