Learning the difference between Equals() and ==
The ==
operator compares object references, known as shallow comparison, while the Equals()
method compares object content, known as deep comparison. Both the operator and the method can be overloaded.
Note
If you overload the ==
operator, then you should overload the Equals()
method and vice versa.
The ==
operator returns true
in the following situations:
Value Type Value == Value Type Value
Reference Type Instance == Reference Type Instance
String == String
The Equals()
method returns true
in the following situations:
ReferenceType.Equals(ReferenceType)
both refer to the same object referenceValueType.Equals(ValueType)
are both the same type and have the same value
Now, let's add a new class called Equality
to the root of the CH06_Collections project to demonstrate the difference in performance between the ==
operator and the Equals()
method. Let's get started:
-
...