In the msdn guide to overriding Equals, why casting to an object in null validation?

I just watched Recommendations on overloading Equals () on msdn (see code below); most of them I understand, but there is one line that I do not get.

if ((System.Object)p == null) 

or, in the second redefinition

 if ((object)p == null) 

Why not just

  if (p == null) 

What is a throw to buy an object?

 public override bool Equals(System.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); } public bool Equals(TwoDPoint p) { // If parameter is null return false: if ((object)p == null) { return false; } // Return true if the fields match: return (x == px) && (y == py); } 
+4
source share
3 answers

The == operator can be overridden, and if so, the default link comparison may not be the same as you. Casting in System.Object ensures that calling == performs a test equality test.

 public static bool operator ==(MyObj a, MyObj b) { // don't do this! return true; } ... MyObj a = new MyObj(); MyObj b = null; Console.WriteLine(a == b); // prints true Console.WriteLine((object)a == (object)b); // prints false 
+10
source

I suppose, as the article also talks about redefining the == operator, that it forces it to use the == operator defined in Object, and not any overloaded operator in the current class.

+2
source

I prefer to use object.ReferenceEquals(a, b) in this ambiguous context to force comparison of links, because it makes the goal clear, while preserving the semantics exactly (in fact, ReferenceEquals is implemented this way).

+2
source

All Articles