Search code examples
c#genericsnulldefault

Differentiate between null and default in generic method


I have a method which supports all kinds of types and there I want to check if the value is null but only for reference types, for value types such check does not make sense. Since this method is deep in the call tree it would be complicated to just duplicate the method for reference types and use class constraint there.

void Foo<T>(T a)
{
   // check for null for reference types only
   if (a == null) 
   {
   }
}

Solution

  • You could use Type.IsValueType if you want to "check for null for reference types only":

    void Foo<T>(T a)
    {
        bool isReferenceType = !typeof(T).IsValueType;
        if (isReferenceType && a == null)
        {
        }
    }
    

    So nullable types(which are structs, hence value types) will not pass this check even if a == null would return true. I guess this is the expected behavior.