I recently got caught out when writing some operator overloading code. I had originally checked if either of the objects were null in order to prevent a null reference exception not realising that the check itself was actually creating an infinite loop. Doh! Below is the correct code skeleton.
public static bool operator == (ObjectType c1,ObjectType c2)
{
if( !(c1 is ObjectType) )
{
return !(c2 is ObjectType);
}
return c1.Equals(c2);
}
public static bool operator != (ObjectType c1, ObjectType c2)
{
if( !(c1 is ObjectType) )
{
return (c2 is ObjectType);
}
return !c1.Equals(c2);
}
public override bool Equals(object obj)
{
if(obj is ObjectType)
{
// do compare logic here
return ((ObjectType)obj).Value == this.Value;
}
else
{
return false;
}
}