Freigeben über


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

  • Anonymous
    May 05, 2006
    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.
  • Anonymous
    May 05, 2006
    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.
  • Anonymous
    May 05, 2006
    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. :)