I want to determine if a generic object type ("T") method type parameter is a collection type. I would typically be sending T through as a Generic.List but it could be any collection type as this is used in a helper function.
Would I be best to test if it implements IEnumerable<T>?
If so, what would the code look like?
Update 14:17 GMT+10 Possibly extending on a solution here (however only works for List<T>'s not IEnumerable<T>'s when it should if List derives ?)
T currentObj;
// works if currentObj is List<T>
currentObj.GetType().GetGenericTypeDefinition() == typeof(List<>)
// does not work if currentObj is List<T>
currentObj.GetType().GetGenericTypeDefinition() == typeof(IEnumerable<>)
In order to get the actual type of T at runtime, you can use the typeof(T) expression. From there the normal type comparison operators will do the trick
Full Code Sample:
Personally I tend to use a method that I wrote myself, called
TryGetInterfaceGenericParameters
, which I posted below. Here is how to use it in your case:Example of use
It is important to note here that you pass in
typeof(IEnumerable<>)
, nottypeof(IEnumerable)
(which is an entirely different type) and also nottypeof(IEnumerable<T>)
for anyT
(if you already know theT
, you don’t need this method). Of course this works with any generic interface, e.g. you can usetypeof(IDictionary<,>)
as well (but nottypeof(IDictionary)
).Method source
I love generics. In this method
T
must have a public and parameterless constructor which means you can not useIList<object>
forT
. You must useList<object>
This will be the simplest check..
You can use Type.GetInterface() with the mangled name.
For simplicity and code sharing, I usually use this extension method: