Checking instance of non-class constrained type parameter for null in generic method

Posted by casperOne on Stack Overflow See other posts from Stack Overflow or by casperOne
Published on 2012-09-12T21:30:31Z Indexed on 2012/09/12 21:38 UTC
Read the original article Hit count: 258

I currently have a generic method where I want to do some validation on the parameters before working on them. Specifically, if the instance of the type parameter T is a reference type, I want to check to see if it's null and throw an ArgumentNullException if it's null.

Something along the lines of:

// This can be a method on a generic class, it does not matter.
public void DoSomething<T>(T instance)
{
    if (instance == null) throw new ArgumentNullException("instance");

Note, I do not wish to constrain my type parameter using the class constraint.

I thought I could use Marc Gravell's answer on "How do I compare a generic type to its default value?", and use the EqualityComparer<T> class like so:

static void DoSomething<T>(T instance)
{
    if (EqualityComparer<T>.Default.Equals(instance, null))
        throw new ArgumentNullException("instance");

But it gives a very ambiguous error on the call to Equals:

Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead

How can I check an instance of T against null when T is not constrained on being a value or reference type?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about null