morleyc
morleyc

Reputation: 2431

Return types of generic interface implementations from a provided type

Given a class that implements an interface:

public interface DomainEventSubscriber<T>
{
    void HandleEvent(T domainEvent);
}

public class TestEventHandler : DomainEventSubscriber<TestEvent1>, DomainEventSubscriber<OtherTestEvent1>
{
    public void HandleEvent(TestEvent1 domainEvent)
    {
    }

    public void HandleEvent(OtherTestEvent1 domainEvent)
    {
        throw new NotImplementedException();
    }
}

I would like to return the types that are implemented, i.e.

static Type[] FindTypesForDomainEventSubscriberOfT(Type type)
{
     // given a TestEventHandler type, I should return a collection of { TestEvent1, OtherTestEvent1 }
}

How can this be done please?

Upvotes: 0

Views: 49

Answers (2)

Venson
Venson

Reputation: 1870

I guess you are looking for the Type.GetGenericTypeDefinition Method

private static void DisplayTypeInfo(Type t)
{
    Console.WriteLine("\r\n{0}", t);
    Console.WriteLine("\tIs this a generic type definition? {0}", 
        t.IsGenericTypeDefinition);
    Console.WriteLine("\tIs it a generic type? {0}", 
        t.IsGenericType);
    Type[] typeArguments = t.GetGenericArguments();
    Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length);
    foreach (Type tParam in typeArguments)
    {
        Console.WriteLine("\t\t{0}", tParam);
    }
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500225

It sounds like you want something like:

static Type[] FindTypesForDomainEventSubscriberOfT(Type type)
{
    return type.GetInterfaces()
      .Where(x => x.IsGenericType &&
                  x.GetGenericTypeDefinition() == typeof(DomainEventSubscriber<>))
      .Select(x => x.GetGenericArguments()[0])
      .ToArray(); 
}

Note that this could end up returning type parameters. For example, if you had:

public class Foo<T> : DomainEventSubscriber<T>

then it would return T, the type parameter for Foo<T>. If you don't want that, you could insert:

.Where(x => !x.IsGenericParameter)

before the ToArray call.

(I'd also recommend that you rename your interface to have an I prefix, following .NET naming conventions.)

Upvotes: 3

Related Questions