开发者

.NET: Strange behaviour of double.Equals() when boxing

What's going on here?

int zero = 0;
double x = 0;
object y = x;

Console.WriteLine(x.Equals(zero)); // True
Console.WriteLine(y.E开发者_StackOverflowquals(zero)); // False


Here, you're calling two different methods - Double.Equals(double) and Object.Equals(object). For the first call, int is implicitly convertable to double, so the input to the method is a double and it does an equality check between the two doubles. However, for the second call, the int is not being cast to a double, it's only being boxed. If you have a look at the Double.Equals(object) method in reflector, the first line is:

if (!(obj is double))
{
    return false;
}

so it's returning false, as the input is a boxed int, not a boxed double.

Good catch!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜