Object base class has the following code which compares equality of two objects
public static bool Equals(Object objA, Object objB)
{
if (objA==objB) {
return true;
}
if (objA==null || objB==null) {
return false;
}
return objA.Equals(objB);
}
What is the difference between comparisons objA==objB
and objA.Equals(objB)
and why do we need to check objA==objB
separately?
UPDATE: The comment in the source code says that "Equality is defined as object equality for reference types and bitwise equality for value types
". Thus if we deal with reference type and objA!=objB
then we must return false
without other comparisons, don't we? objA.Equals(objB)
looks redundant here.
The first comparison is a simple reference identity comparison - in other words, do the values of objA
and objB
refer to the same object (or are both null). This has two purposes in Equals(object, object)
:
Equals
Equals(null, null)
return true without having to have a special case for itobjA.Equals(objB)
calls the virtual object.Equals(object)
method, which can be overridden in subclasses. (An Equals
implementation typically starts off with the same reference comparison as we've already performed, again for optimization purposes... it's a bit of a shame to have the same comparison twice, but it makes sense to avoid a virtual call when we don't need it.)
For example, string
overrides Equals
so that two independent string
objects can still be equal to each other. (string
also overloads the ==
operator to have the same meaning as Equals
, but that's irrelevant in the Equals(object, object)
code, as overloading is a compile-time matter... the ==
in Equals(object, object)
will only ever perform a reference comparison.)
EDIT: The comment about "Equality is defined as object equality for reference types and bitwise equality for value types" is the default implementation of Equals
(that's where the comment occurs). It has nothing to do with ==
, and that behaviour can be overridden by overriding Equals
further.
See more on this question at Stackoverflow