This question already has an answer here:
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?
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.
the below is the line that does the cast
the difference with the "normal" cast is that using "As" it doesn't raise an exception if the object is not "castable". In this case if "p" is not a
TwoDPoint
Type is not gonna raise an exception (cast not valid) but return null.this code check if the cast went fine if not p should be null for the reason above
This is not useless. Without that cast the == operator being overloaded would be called recursively...
To force it to use the Equals method of Object rather than its own overloaded version... just a guess...
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
.Note that this is the VS 2005 documentation. I guess the folks who write the documentation also had the same question and couldn't come up with a good answer; the example was changed for VS 2008. Here is the current version: