Wednesday, November 22, 2006

Quick Tip: Checking for a reference type null in C#

How do you test for a null reference type in C#?

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))
return true;

// one null => not equal
if (IsNull(thing1) || IsNull(thing2))
return false;

// do the REAL equality test here
...
}

Simple when you know how! And absolutely essential when you're implementing IEquatable.

3 comments:

Joel Hammond-Turner said...

Update: Of course, I should really have been using to check for a null reference in IsNUll is the Object.ReferenceEquals method:

return Object.ReferenceEquals(thing, null)

Saves on all that casting (and hence improves performance)

Unknown said...

Thank you - just what I needed!

Unknown said...

Thank you - just what I needed!