Problem Of Null Check To Overloaded Operator==

Recently I've added simple data class named FPoint which expands windows Point class with x, y, z as double to use basic arithmetic operations easily. My coworker added an equality operator overloading as following

public static bool operator ==(FPoint fp1, FPoint fp2)
{
    return ((fp1.X == fp2.X) && (fp1.Y == fp2.Y) && (fp1.Z == fp2.Z));
}

And this guy crashes when either fp1 or fp2 were null since fp1.X cannot be evaluated.
I could use exception handling but decided to perform null check to make sure.

public static bool operator ==(FPoint fp1, FPoint fp2)
{
    if (fp1 == null || fp2 == null)
        return false; 
    else 
        return ((fp1.X == fp2.X) && (fp1.Y == fp2.Y) && (fp1.Z == fp2.Z));
}

And the above code cause stack overflow! After spending long time, I realize "fp1 == null" may call this function recursively since fp1 itself is same type with this. So, how to solve this problem? How's reversing the comparisons?

public static bool operator ==(FPoint fp1, FPoint fp2)
{
    if (null == fp1 || null == fp2)
        return false; 
    else 
        return ((fp1.X == fp2.X) && (fp1.Y == fp2.Y) && (fp1.Z == fp2.Z));
}

Doesn't work neither.

It was simpler than I thought when I got solution after having meditation on it over an hour.
Just cast it to something else!

public static bool operator ==(FPoint fp1, FPoint fp2)
{
    if ((object)fp1 == null || (object)fp2 == null)
        return false; 
    else 
        return ((fp1.X == fp2.X) && (fp1.Y == fp2.Y) && (fp1.Z == fp2.Z));
}

And it works when one of them is null. What if both of them are null? Thus, I want to get true when something's really null.

public static bool operator ==(FPoint fp1, FPoint fp2)
{
    if ((object)fp1 == null && (object)fp2 == null)
        return true; 
    else if ((object)fp1 == null || (object)fp2 == null)
        return false; 
    else 
        return ((fp1.X == fp2.X) && (fp1.Y == fp2.Y) && (fp1.Z == fp2.Z));
}

We still need those kind of comparisons even with exception handling to get correct answer.
So, it's good to know when we got similar situation with type compared to non typed value (or parent typed).

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License