Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

== and Equals. Why the complexity? [closed]

Tags:

c#

With == operator I can do this:

int a = 10;
int b = 10;
a==b //true

In this case C# makes a compile-time decision, and no virtual behavior comes into play.

But, if I use:

object a = 10;
object b = 10;
a == b //false

The result is false because object is a class (reference type) and a and b each refer to different boxed objects on the heap.

To solve it I should do:

object a = 10;
object b = 10;
a.Equals (b) // True

Because Equals is a virtual method and it is resolved at runtime depending of the objects’s actual type.

My question is:

Why the designers of C# didn’t avoid the problem by making == virtual, and so functionally identical to Equals?

like image 591
Pablo Claus Avatar asked Dec 07 '22 12:12

Pablo Claus


1 Answers

Because == is a static method, so cannot be virtual. This was probably done to better handle null.

Note that your dilemma has nothing to do with boxing, C# uses the compile time type of both parameters to determine what overload* of == makes sense. For instance, take the following example.

object s1 = "Hello";
object s2 = new String('H', 'e', 'l', 'l', 'o');
s1 == s2; //False
(string)s1 == (string)s2; //True

* Overload is not absolutely correct, since we are searching more than one class hierarchy, but it is close enough semantically for the discussion.

like image 140
Guvante Avatar answered Dec 10 '22 03:12

Guvante