Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.Equals(zero)); // False
like image 913
Vilx- Avatar asked May 06 '10 09:05

Vilx-


1 Answers

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!

like image 70
thecoop Avatar answered Sep 23 '22 05:09

thecoop