Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between double? and int? for .Equals comparisons?

Tags:

c#

nullable

I have a very strange situation I don't understand. Below is the case simplified:

double? d = 2;
int? i = 2;

Console.WriteLine(d.Equals((2))); // false
Console.WriteLine(i.Equals((2))); // true

I don't understand why one expression will net me true and another false. They seem identical.

like image 854
Iteria Avatar asked Sep 26 '18 18:09

Iteria


People also ask

Can we compare double with int?

It is valid, but you may get interesting results in edge cases if you don't specify a precision on the double...

Can you use == for doubles?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result. For this reason, we must use a more complex comparison algorithm.

Can you compare int and double in C++?

If you're comparing int s to double s you're going to need to come up with whatever rules you want to use when determining if two values are "close enough." You may consider using the std::modf function (in <cmath> ) in making the comparison.

What is difference between A Equals B and a == b?

== operator compares reference returns true when both references point to the same object and Equals() compares object by value and it will return true if the references refers object which are equivalent.


1 Answers

You are completely right to find this confusing. It is a mess.

Let's start by clearly saying what happens by looking at more examples, and then we will deduce the correct rules that are being applied here. Let's extend your program to consider all these cases:

    double d = 2;
    double? nd = d;
    int i = 2;
    int? ni = i;
    Console.WriteLine(d == d);
    Console.WriteLine(d == nd);
    Console.WriteLine(d == i);
    Console.WriteLine(d == ni);
    Console.WriteLine(nd == d);
    Console.WriteLine(nd == nd);
    Console.WriteLine(nd == i);
    Console.WriteLine(nd == ni);
    Console.WriteLine(i == d);
    Console.WriteLine(i == nd);
    Console.WriteLine(i == i);
    Console.WriteLine(i == ni);
    Console.WriteLine(ni == d);
    Console.WriteLine(ni == nd);
    Console.WriteLine(ni == i);
    Console.WriteLine(ni == ni);
    Console.WriteLine(d.Equals(d));
    Console.WriteLine(d.Equals(nd));
    Console.WriteLine(d.Equals(i));
    Console.WriteLine(d.Equals(ni)); // False
    Console.WriteLine(nd.Equals(d));
    Console.WriteLine(nd.Equals(nd));
    Console.WriteLine(nd.Equals(i)); // False
    Console.WriteLine(nd.Equals(ni)); // False
    Console.WriteLine(i.Equals(d)); // False
    Console.WriteLine(i.Equals(nd)); // False
    Console.WriteLine(i.Equals(i)); 
    Console.WriteLine(i.Equals(ni));
    Console.WriteLine(ni.Equals(d)); // False
    Console.WriteLine(ni.Equals(nd)); // False
    Console.WriteLine(ni.Equals(i)); 
    Console.WriteLine(ni.Equals(ni));

All of those print True except the ones I have notated as printing false.

I'll now give an analysis of those cases.

The first thing to notice is that the == operator always says True. Why is that?

The semantics of non-nullable == are as follows:

int == int -- compare the integers
int == double -- convert the int to double, compare the doubles
double == int -- same
double == double -- compare the doubles

So in every non-nullable case, integer 2 is equal to double 2.0 because the int 2 is converted to double 2.0, and the comparison is true.

The semantics of nullable == are:

  • If both operands are null, they're equal
  • If one is null and the other is not, they're unequal
  • If both are not null, then fall back to the non-nullable case above.

So again, we see that for the nullable comparisons, int? == double?, int? == double, and so on, we always fall back to the non-nullable cases, convert the int? to double, and do the comparison in doubles. Thus these are also all true.

Now we come to Equals, which is where things get messed up.

There is a fundamental design problem here, which I wrote about in 2009: https://blogs.msdn.microsoft.com/ericlippert/2009/04/09/double-your-dispatch-double-your-fun/ -- the problem is that the meaning of == is resolved based on the compile time types of both operands. But Equals is resolved on the basis of the run time type of the left operand (the receiver), but the compile time type of the right operand (the argument), and that's why things go off the rails.

Let's begin by looking at what double.Equals(object) does. If the receiver of a call to Equals(object) is double then if the argument is not a boxed double, they are considered not equal. That is, Equals requires that the types match, whereas == requires that the types be convertible to a common type.

I'll say that again. double.Equals does not try to convert its argument to double, unlike ==. It just checks to see if it already is double, and if it is not, then it says they are not equal.

That then explains why d.Equals(i) is false... but... wait a minute, it is not false above! What explains this?

double.Equals is overloaded! Above we are actually calling double.Equals(double), which -- you guessed it -- converts the int to a double before doing the call! If we had said d.Equals((object)i)) then that would be false.

All right, so we know why double.Equals(int) is true -- because the int is converted to double.

We also know why double.Equals(int?) is false. int? is not convertible to double, but it is to object. So we call double.Equals(object) and box the int, and now its not equal.

What about nd.Equals(object) ? The semantics of that is:

  • If the receiver is null and the argument is null, they are equal
  • If the receiver is not null then defer to the non-nullable semantics of d.Equals(object)

So now we know why nd.Equals(x) works if x is a double or double? but not if it is int or int?. (Though interestingly, of course (default(double?)).Equals(default(int?)) would be true since they are both null!)

Finally, by similar logic we see why int.Equals(object) gives the behaviour it has. It checks to see if its argument is a boxed int, and if it is not, then it returns false. Thus i.Equals(d) is false. The i cannot be converted to double, and the d cannot be converted to int.

This is a huge mess. We would like equality to be an equivalence relation, and it is not! An equality relationship should have these properties:

  • Reflexivity: a thing is equal to itself. That is usually true in C# though there are a few exceptions.
  • Symmetry: If A is equal to B then B is equal to A. That is true of == in C# but not of A.Equals(B), as we've seen.
  • Transitivity: If A equals B and B equals C then A also equals C. That is absolutely not the case in C#.

So, its a mess on all levels. == and Equals have different dispatch mechanisms and give different results, neither of them are equivalence relations, and it's all confusing all the time. Apologies for getting you into this mess, but it was a mess when I arrived.

For a slightly different take on why equality is terrible in C#, see item number nine on my list of regrettable language decisions, here: http://www.informit.com/articles/article.aspx?p=2425867

BONUS EXERCISE: Repeat the above analysis, but for x?.Equals(y) for the cases where x is nullable. When do you get the same results as for non-nullable receivers, and when do you get different results?

like image 125
Eric Lippert Avatar answered Sep 19 '22 19:09

Eric Lippert