What do you think will be the output in the code snippet below?

 

object o1 = 5;

object o2 = 5;

 

System.Diagnostics.Debug.WriteLine(o1 == o2);

System.Diagnostics.Debug.WriteLine(o1.Equals(o2));

System.Diagnostics.Debug.WriteLine(((Int32) o1).CompareTo(o2));

 

If you answered

False

True

0

you’re correct!

 

As it turns out, Int32 type (implemented as struct) overrides Equals method, but not == operators.  So == compares references, while Equals compares underlying values.

 

 

Personally, whenever I override the Equals method, I always override == and != operators and GetHashCode to avoid this un-intuitive behavior.