How do I put all types implementing a certain generic interface in a dictionary?

Posted by James Wenday on Stack Overflow See other posts from Stack Overflow or by James Wenday
Published on 2010-05-24T12:12:41Z Indexed on 2010/05/24 12:31 UTC
Read the original article Hit count: 236

Filed under:
|
|

Given a particular interface ITarget<T> and a particular type myType, here's how you would determine T if myType implements ITarget<T>. (This code snippet is taken from the answer to an earlier question.)

foreach (var i in myType.GetInterfaces ())
    if (i.IsGenericType
        && i.GetGenericTypeDefinition() == typeof(ITarget<>))
        return i.GetGenericArguments ()[0] ;

However, this only checks a single type, myType. How would I create a dictionary of all such type parameters, where the key is T and the value is myType? I think it would look something like this:

var searchTarget = typeof(ITarget<>);
var dict = Assembly.GetExecutingAssembly().[???]
             .Where(t => t.IsGenericType
                    && t.GetGenericTypeDefinition() == searchTarget)
             .[???];

What goes in the blanks?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics