Reflection on Generic Types

I really love Generics in .Net 2.0 - I think they're great.  They remove a lot of that nasty casting to objects which we had to do in .Net 1.x and they generally improve type-safety.  However, I recently hit a problem when trying to do some reflection against generic types.

I have a generic interface ICustomDataMapper<T>.  I want to know, programatically, if a Type t which has been passed to my method implements this interface, or at least a closed version thereof.  The best I could come up with was:

bool DoesImplement = false;
foreach (Type intface in t.GetInterfaces())
{
     if (intface.IsGenericType &&
        intface.GetGenericTypeDefinition().Name.StartsWith
              
("ICustomDataMapper"))
     DoesImplement =
true;
}

This is a bit rubbish.  Can anyone show me a better way?

August 7 2006
blog comments powered by Disqus