Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
514 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...