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

前端 未结 3 2069
遥遥无期
遥遥无期 2020-12-06 00:17

I\'d like to know what is default implementation for equality operatort (== and !=)

Is it?

public static bool operator ==(object obj1, object obj2)
{         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 00:51

    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.

提交回复
热议问题