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).
One of recent trend of coding style is like this
if (null==myVar) { … }
The benefit of doing this is a lot but the one related to the above posting is simpler codes. We don't really need type casting by reversing the comparison orders. Thing's changed fast and hard to catch up.
Post preview:
Close preview