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?
I assume that you don't just want to know if the type is generic, but if an object is an instance of a particular generic type, without knowing the type arguments.
It's not terribly simple, unfortunately. It's not too bad if the generic type is a class (as it is in this case) but it's harder for interfaces. Here's the code for a class:
EDIT: As noted in comments, this may work for interfaces:
I have a sneaking suspicion there may be some awkward edge cases around this, but I can't find one it fails for right now.
You can use shorter code using dynamic althougth this may be slower than pure reflection:
If you want to check if it's an instance of a generic type:
If you want to check if it's a generic
List<T>
:As Jon points out, this checks the exact type equivalence. Returning
false
doesn't necessarily meanlist is List<T>
returnsfalse
(i.e. the object cannot be assigned to aList<T>
variable).These are my two favorite extension methods that cover most edge cases of generic type checking:
Works with:
Has an overload that will 'out' the specific generic type if it returns true (see unit test for samples):
Here's a test to demonstrate the (basic) functionality: