You'd think that it'd be easy to check for a null, just use some code like this:
MyType thing = null;
if ( thing == null)
// do something
But what if you need to test for a null within an overloaded == operator?! You can't use the simple code above, as this would cause a stack overflow.
The trick is in casting the entity to a different type and so that the compiler uses the == for that alternate type. I wrap this test into a static IsNull() method on the class.
public static bool IsNull(MyType thing)
object testThing = thing as object;
// uses the == operator from object, NOT MyType
return (testThing == null);
So now I can safely test for equality, including correctly testing for nulls like this
public static bool operator == (MyType thing1, MyType thing2)
// two nulls => equal
if (IsNull(thing1) && IsNull(thing2))
// one null => not equal
if (IsNull(thing1) || IsNull(thing2))
// do the REAL equality test here
Simple when you know how! And absolutely essential when you're implementing IEquatable.