Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast to object before null check in overriding Equals [duplicate]

Just reading the msdn article on overriding equality operators here

The following snippet confuses me...

// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null) // <-- wtf?
{
    return false;
}

Why is there a cast to Object here to perform the null comparison?

like image 689
fearofawhackplanet Avatar asked Feb 04 '23 01:02

fearofawhackplanet


2 Answers

Operators apply through static analysis (and overloads), not virtual methods (overrides). With the cast, it is doing a reference equality check. Without the cast, it can run the TwoDPoint operator. I guess this is to avoid problems when an operator is added.

Personally, though, I'd do a reference check explicitly with ReferenceEquals.

like image 70
Marc Gravell Avatar answered Feb 05 '23 15:02

Marc Gravell


No! if you don't do that, the runtime will start a recursive call to the equality operator you are just in which results in infinite recursion and, consequently, a stack overflow.

like image 24
Paul Michalik Avatar answered Feb 05 '23 15:02

Paul Michalik