Effective C #: overriding Object.Equals (), yay or nay?

In the second issue of Effective C # (ISBN-13: 978-0321658708) on page 37, the book reads

The second function you will never override is static Object.Equals ()

However, on page 39, the book reads

The fact is that if your type must follow the semantics of values ​​(comparing the contents) instead of the reference semantics (comparing the identifier of the object), you must write your own instance override of the Object.Equals ()

Would someone be so kind as to explain why one could override

public virtual bool Equals(object right); 

but not

 public static bool Equals(object left, object right); 

Thanks:)

+4
source share
4 answers

Because you cannot override the static method.

+8
source

The first thing to clarify is that you cannot override static methods. Implementation

 public static bool Equals(object left, object right); 

cannot be overridden. The static equals method is intended only to prevent null checking. Inside, it first checks the reference equals, and then equal the contents (non-stationary equals method).

In the above quotes, the first quote refers to the static equal method, where, since the second refers to the non static equals method, both are written in notation as Object.Equals (), but note that the first says "static Object.Equals ()"

+2
source

never override static Object.Equals ()

You must write your own instance override for Object.Equals ()

Note the difference, static instance vs. These sentences do not apply to the same method ...

+1
source

In addition, if I'm not mistaken, the static only compares the link, where, since virtual gives you the opportunity to write your own comparison, which in most cases is based on values, not on links.

+1
source

All Articles