Height implements the operators, here is the current implantation of == operator …
public static bool operator ==(Height a, Height b)
{
return a.CMValue == b.CMValue;
}
#1 – What’s wrong with this code?
What happens if you want to do the following:
Height a = new Height(100);
Height b = null;
a == b
This will result in NullReferenceException … bad bad bad
Ok lets fix this …
public static bool operator ==(Height a, Height b)
{
if( a == null && b == null) return true;
if( a == null || b == null) return false;
return a.CMValue == b.CMValue;
}
#2 – What’s wrong with this code?
Do you see the recursiveness here?
a == null will call the same implementation, resulting in NullReferenceException … bad bad bad
Ok lets fix this…
public static bool operator ==(Height a, Height b)
{
object _a = (object)a, _b = (object)b;
if (_a == null && _b == null) return true;
if (_a == null || _b == null) return false;
return a.CMValue == b.CMValue;
}
By converting a and b to objects, we are using object’s implementation of the == operator, thus avoiding a recursive call.


0 comments:
Post a Comment