Suppose I define two tuples:
Tuple<float, float, float, float> tuple1 = new Tuple<float, float, float, float>(1.0f, 2.0f, 3.0f, 4.0f);
Tuple<float, float, float, float> tuple2 = new Tuple<float, float, float, float>(1.0f, 2.0f, 3.0f, 4.0f);
If I try to compare the tuples, I get different results
bool result1 = (tuple1 == tuple2); // FALSE
bool result2 = tuple1.Equals(tuple2); // TRUE
I would expect for both calls to return true. What exactly is == comparing?
For Tuple, the == is comparing the object references because it does not overload the
==operator. Since the objects are equivalent, but not the same specific instance,Equals()returnstrueand==returnsfalse.Many types do not overload
==, some prefer to keep a distinction betweenEquals()for equivalence and==for reference equality.In addition, relying on
==for equivalence can lead to some weirdness:The code above will always check for reference equality because an unconstrained generic is considered an
objectat compile time, thus if the method isn’t virtual, you will get object’s version (even if the type, such asstringoverloads==).Thus this usage of the above code:
Yes, the strings are equivalent, yes
Tisstring, but the==is bound to object’s==since the generic is unconstrained, thus this will returnfalseeven though the same code with explicitstringparameters would returntrue.