开发者

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

开发者 https://www.devze.com 2022-12-29 03:20 出处:网络
What\'s going on here? int zero = 0; double x = 0; object y = x; Console.WriteLine(x.Equals(zero)); // True

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

精彩评论

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