C#: Default implementation for == and != operators for objects

No, it’s not that – by default, references are checked for equality. Operators such as == are not polymorphic and don’t call anything polymorphic by default. So for example:

string x = "Hello";
string y = new String("Hello".ToCharArray());
Console.WriteLine(x == y); // True; uses overloaded operator

object a = x;
object b = y;
Console.WriteLine(a == b); // False; uses default implementation

You can’t override equality operators, but you can overload them, as string does. Whether or not you should is a different matter. I think I usually would if I were overriding Equals, but not necessarily always.

Leave a Comment