C#: Default implementation for == and != operators for objects
I'd like to know what is default implementation for equality operatort (== and !=)
Is it?
public static bool operator ==(object obj1, object obj2)
{
return obj1.Equals(obj2);
}
public static bool operator !=(object obj1, object obj2)
{
return !obj1.Equals(obj2);
}
So I only need to override Equals method or do I need to override euality operators as well ?开发者_C百科
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.
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).
By default, those operators test for equality of reference.
精彩评论