Finding out if a type implements a generic interface
.net, c#, reflection
Solution
// this conditional is necessary if myType can be an interface,
// because an interface doesn't implement itself: for example,
// typeof (IList<int>).GetInterfaces () does not contain IList<int>!
if (myType.IsInterface && myType.IsGenericType &&
myType.GetGenericTypeDefinition () == typeof (IList<>))
return myType.GetGenericArguments ()[0] ;
foreach (var i in myType.GetInterfaces ())
if (i.IsGenericType && i.GetGenericTypeDefinition () == typeof (IList<>))
return i.GetGenericArguments ()[0] ;
Edit: Even if `myType` implements `IDerivedFromList<>` but not directly `IList<>`, `IList<>` will show up in the array returned by `GetInterfaces()`.
Update: added a check for the edge case where `myType` is the generic interface in question.
Problem
Let's say I have a type, MyType. I want to do the following: - Find out if MyType implements the IList interface, for some T. - If the answer to (1) is yes, find out what T is. It seems like the way to do this is GetInterface(), but that only lets you search by a specific name. Is there a way to search for "all interfaces that are of the form IList" (If possible it woudl also be useful if it worked if the interface was a subinterface of IList.) Related: How to determine if a type implements a specific generic interface type