Here is an interesting description of the differences between Object Identity and Object Equality pertaining to objects in the .NET Framework.
Generally speaking, two objects are identical if they share the same address in memory. This means that they are both referring to the same instance of a class. You can test if two objects are identical by using the ReferenceEquals static method of System.Object: Object.ReferenceEquals(myFirstObject, mySecondObject).
On the other hand, two objects are equivalent if they are instances of the same type and if every field of the first object matches the value of the same field of the second object. Being equivalent does not imply that the objects are identical: they can be independent instances, but their fields should have the same value. Because testing for equivalence can and probably will be different for most types, there is no global solution. For this purpose System.Object provides the virtual (overridable) method Equals to determine if two objects are equal. When implementing the overridden method, you need to ensure that the operation is:
- Reflexive:
myObject.Equals(myObject) must be true
- Symmetric:
if myFirstObject.Equals(mySecondObject) is true then mySecondObject.Equals(myFirstObject) must also be true
- Transitive:
if myFirstObject.Equals(mySecondObject) is true and
mySecondObject.Equals(myThirdObject) is true then
myFirstObject.Equals(myThirdObject) must be true too.
The interesting thing is that if you don't override the virtual method Equals of System.Object when creating your own objects, the virtual method Equals looks like this:
class Object {
public virtual Boolean Equals(Object obj) {
// If both references point to the same
// object, they must be equal.
if (this == obj) return (true);
// Assume that the objects are not equal.
return (false);
}
...
}
So really, the virtual method Equals of System.Object only tests if the two objects are identical (share the same address in memory) not equivalent. You will need to override this method if you want Equals to act any differently.