When programming in C#, we often test if a variable is used in the following way:

if (var != null) {
  // do the right thing
}
else
{
  // fallback or raise exception
}

This works well if the variable is a nullable type or a reference type, but when the variable is of a non nullable type it will raise an exception. This also works the other way around, when you test a reference typed by comparing it to 0, chances are quite big the runtime will also raise an exception.

Now you’re probably thinking it’s impossible to do this, because the compiler will warn you about this and it simply won’t compile. True, except when we don’t know the type beforehand, which usually is the case when using generics.

Take a look at this code:

public bool isValueSet<T>(T source)
{
  return source != null;
}

This piece of code works almost exactly as the first code fragment in this post, though here it has room for the aforementioned caveat. We don’t know if the type T is a reference type or a value-type. There are more ways to make it work exactly how it’s intended.

  1. Setup a control flow which switches between value-types and other types (reference types) using the GetType().IsValueType property
  2. Use the default(T) construction, so the framework will automatically assigns the default value according to the given type. I myself prefer this solution.

When using the default(T) following code should always work as expected:

public bool isValueSet<T>(T source)
{
  return source != default(T);
}

long live the framework 🙂