Wednesday 14 September 2011

Dot.Net: Generic List - test Subclass of IEnumerable

Question:
How to test if a given generic list type (e.g. List<>) implements an interface (e.g. IEnumerable<> or IEnumerable)?
How to check interface implementation for generic types? (IsSubclassOf does not work)


Answer:
To test if a type T1 inherites from T2 you do this:
t1.IsSubclassOf(typeof(t2))

To test if a type implements an interface like IEnumerable you write:
t1.IsSubclassOf(typeof(IEnumerable))

But this does not work for generics!
If t1 is a generic list (List<>, type: System.Collections.Generic.List`1) then it implements IEnumerable, but if you do the test:

t1.IsSubclassOf(typeof(IEnumerable))

It turns out that this returns false.

 Instead you have to ask your type if it knows this interface using GetInterface(...) method. If this method returns something, then the type implements this interface.

So, on generic types you can test interface implementation like this:
Type t1 = typeof(List<>);
if (t1.GetInterface("IEnumerable`1") != null)
{
	System.Console.WriteLine("List<> inherits from IEnumerable`1");
}
if (t1.GetInterface("IEnumerable") != null)
{
	System.Console.WriteLine("List<> inherits from IEnumerable");
}
Happy programming ... Jens

No comments: