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

前端 未结 3 2050
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • 2020-12-06 00:56

    By default, those operators test for equality of reference.

    0 讨论(0)
  • 2020-12-06 01:05

    The C# language specification, Section 7.9 covers the exact behavior of the built-in == operator. For example, when using == on reference-type values, the following section applies:

    7.9.6 Reference type equality operators

    The predefined reference type equality operators are:

    bool operator ==(object x, object y);
    bool operator !=(object x, object y);

    The operators return the result of comparing the two references for equality or non-equality.

    Since the predefined reference type equality operators accept operands of type object, they apply to all types that do not declare applicable operator == and operator != members. Conversely, any applicable user-defined equality operators effectively hide the predefined reference type equality operators.

    [More details skipped...]

    Note that "comparing two references for equality" does not mean "the result of calling obj1.Equals(obj2)". It means that both references must point to the same object (reference equality).

    0 讨论(0)
提交回复
热议问题