Strange equality equation listing provided by MSDN

I am looking at an article from the MSDN Recommendations for Overloading Equals () and Operator ==

and I saw the following code

public override bool Equals(object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. TwoDPoint p = obj as TwoDPoint; if ((System.Object)p == null) { return false; } // Return true if the fields match: return (x == px) && (y == py); } 

A strange thing is a throw for an object in the second if

 // If parameter cannot be cast to Point return false. TwoDPoint p = obj as TwoDPoint; if ((object)p == null) { return false; } 

Why does p return to the object again? Isn't it enough to write this

 // If parameter cannot be cast to Point return false. TwoDPoint p = obj as TwoDPoint; if (p == null) { return false; } 

If p cannot be passed to TwoDPoint, then this value will be null. Iโ€™m puzzled, I probably donโ€™t understand something trivial ...

EDIT

Another such cast is presented in another Equals method.

 public bool Equals(TwoDPoint p) { // If parameter is null return false: if ((object)p == null) { return false; } } 

Here again, it is enough to check only if(p == null)

+5
source share
3 answers

(object)p == null uses the built-in == operator, which in this case checks for referential equality. p == null will cause an overloaded operator== for the specified type. If the overloaded operator== is implemented in terms of Equals (this is not the case in the sample you are referencing), then you will have infinite recursion. Even if it is not implemented in terms of Equals , it will still do more than necessary.

+7
source

To complete both answers, the documentation you are looking at is out of date, as indicated at the top of the page. If you look at the newer recommendations , there is a note that explains why this is done:

A common mistake in overloading the == operator is to use (a == b), (a == null) or (b == null) to check for reference equality. Instead, it creates a call to the overloaded operator ==, causing an infinite loop. Use ReferenceEquals or apply a type to an object to avoid a loop.

Basically, this means using object.ReferenceEquals , which is really trying to make code:

 TwoDPoint p = obj as TwoDPoint; if (object.ReferenceEquals(p, null)) { return false; } 
+4
source

This should ensure that the named == operator is the default implementation of Object, not a user-defined one. A common mistake is to introduce unlimited recursion into the code, for example, by calling your own operators.

+2
source

Source: https://habr.com/ru/post/1232345/


All Articles