Richbits Richbits - 1 month ago 8
C# Question

Testing if object is of generic type in C#

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

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).