Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# System.Object.operator==()

Tags:

c#

I'm tryign to get my head around the use of System.Object.operator==().

My Effective C# book, and the page here (http://www.srtsolutions.com/just-what-is-the-default-equals-behavior-in-c-how-does-it-relate-to-gethashcode), says that:

"System.Object.operator==() will call a.Equals(b) to determine if a and b are equal".

So with my code:

   object a = 1;
   object b = 1;

   if(object.Equals(a, b))
   {
    // Will get here because it calls Int32.Equals(). I understand this.

   }

   if(a == b)
   {
    // I expected it to get here, but it doesn't.
   }

I expected (a == b) to call Int32's overriden Equals and compare values in the same way that static objet.Equals() does. What am I missing?

Edit: I should perhaps have added that I can see what (a == b) is testing - it's testing reference equality. I was thrown by the book which seems to suggest it will work internally much as static object.Equals(obect, object) will.

like image 705
MrNick Avatar asked Nov 18 '10 14:11

MrNick


1 Answers

I'm not sure why the book would say that; it is emphatically untrue that the default == calls Equals. Additionally, object does NOT overload ==. The operator == by default performs a value-equality comparison for value types and a reference-equality comparison for reference types. Again, it is NOT overloaded for object (it is for string). Therefore, when you compare object a = 1 and object b = 1 using the == operator you are doing a reference-equality comparison. As these are different instances of a boxed int, they will compare differently.

For all that are confused by this issue, I encourage you to read §7.10 and especially §7.10.6 of the specification extremely carefully.

For more on the subtleties of boxing (or why we need it in the first place), I refer you to a previous post on this subject.

like image 196
jason Avatar answered Sep 19 '22 13:09

jason