My method receives two parameters, both of Object
type. They have the same type, that implements IEquatable
.
My question is: when I do: param1 == param2
does the framework compare using the IEquatable
operator override of specific class or does it uses the object.Equals
that just compares the memory pointer of two objects?
Which is the best way to do this? Is with generics and derivation constraints?
Actually, it does neither. The
==
operator by default will test for reference equality, regardless of the overridden behavior of yourEquals
method (if you've overridden it, which you certainly should have if you implementedIEquatable<T>
).That is to say, if your variables are typed as
object
but you want to use your own custom equality comparison, useEquals(x, y)
rather thanx == y
.Then, even if you've implemented
IEquatable<T>
, be sure to still overrideobject.Equals
, like this:While you certainly can also overload the
==
and!=
operators for your type, this won't accomplish anything if you have references to objects of this type that are simplyobject
variables, like this:The above won't work as you might expect (if you've overloaded
==
and expect that to be used) because the==
overload has to be resolved at compile-time; sincex
andy
are typed as arbitrary objects, the C# compiler will pick theobject
type's==
operator, which, again, just tests for reference equality.Update: Now, you can ensure your
==
operator is used if your variables are typed as the class wherein you defined it or a more derived type. For example, given the following types:The
AComparer<T>.CompareEqual
method above will use your overloaded==
operator for any typeT
deriving fromA
.The key thing to remember is that
==
is static, which means its overload resolution gets performed at compile-time, not at run-time using a vtable (unless you're usingdynamic
, but that's a whole other beast). So just be aware of that whenever you're using the==
operator in code and you want the overload to resolve to that of your custom type.