This is how:
static Type GetGenericListElementType(Type candidateListType) {
Type[] interfaces = candidateListType.GetInterfaces();
foreach (Type interfaceType in interfaces)
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList<>)) {
Type[] genericArguments = interfaceType.GetGenericArguments();
if (genericArguments.Length != 1) return null;
return genericArguments[0];
}
return null;
}
static bool IsIList(Type candidateListType) { return GetGenericListElementType(candidateListType) != null); }
object someObject =
if (someObject != null) {
bool isIList = IsIList(someObject.GetType());
}
Not only this code answers the question, it also determines the element type of the generic list. This code is non-trivial in the following sense: it shows how to work with the type which is not fully defined, when the you know only the non-instantiated generic type (
IList<>
).
Needless to say, in new development
you should only use strongly-typed generic list types and interfaces, never the weak-typed non-generic collections. If you still need it by whatever reason (legacy?), you could easily simplify the above code simply checking:
Type typeInQuestion =
bool isIList = typeof(System.Collections.IList).IsAssignableFrom(typeInQuestion);
[EDIT]
Solution 1 shows even simper and, most likely, faster method. Consider my answer as focused on the problem of generic collection and the overkill :-). I just want to emphasize that non-generic collections are not useful. There is no such thing as .NET Framework prior to 2.0; I think those old versions makes little sense if any at all.
[END EDIT]
But again, never use non-generic
System.Collections.IList
in any new development.
It makes no sense at all, only good to support legacy code. The non-generic (non-specialized) collections was rendered obsolete as early as of .NET Framework v.2.0. These types were not formally marked with
obsolete
attribute only because there is nothing wrong in these types if there were introduced in legacy code.
The problem is fully solved. Enjoy. :-)
—SA