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)
source share