Testing if object is of generic type in C#

Richbits picture Richbits · Jun 11, 2009 · Viewed 70.5k times · Source

I would like to perform a test if an object is of a generic type. I've tried the following without success:

public bool Test()
{
    List<int> list = new List<int>();
    return list.GetType() == typeof(List<>);
}

What am I doing wrong and how do I perform this test?

Answer

Mehrdad Afshari picture Mehrdad Afshari · Jun 11, 2009

If you want to check if it's an instance of a generic type:

return list.GetType().IsGenericType;

If you want to check if it's a generic List<T>:

return list.GetType().GetGenericTypeDefinition() == typeof(List<>);

As Jon points out, this checks the exact type equivalence. Returning false doesn't necessarily mean list is List<T> returns false (i.e. the object cannot be assigned to a List<T> variable).