SYSK 120: When == is not same as Equals


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.


 

Comments (3)

  1. hasanib says:

    But even if int32 did implement the static in/equaility methods, i don’t think it would have been called because you boxed the int32 method.

  2. Peter Ritchie says:

    That’s the same for all built-in types, no?  I’ve only had first-hand observance of the above with Int32, Single and Decimal.

  3. macbirdie says:

    I think the == behavior should be consistent all the way – either class specific or to compare references. Not mixed. I sure hope that’s the case throughout the .net class library otherwise it would be confusing, especially for Java programmers. :)