Comparing a generic to its default value

This is a very short post on something which, for some reason, I keep forgetting and having to find code I’ve written in the past to refresh my memory – so I thought I’d write a quick post to remind myself about this.

So you have a generic type T. Maybe it’s passed as an argument to a method and you want to check whether it’s set to its default value (in the case of classes this is equivalent to null).

To do this we use the following code (where o is the variable name of some generic type)

if(EqualityComparer<T>.Default.Equals(o, default(T))) 
{
   // do something
}

As previously stated – for class types, this is equivalent to null, for other types it depends upon their default value.

This code will handle structs and classes as well as Nullable types and also avoids boxing (see C# 5.0 in a Nutshell).