morleyc
morleyc

Reputation: 2431

Get list of type(s) of specific interface implemented by concrete class

Given a class, how can i find the types for the INotificationHandler<>:

public class OtherClass : INotificationHandler<Aggregate>, INotificationHandler<Quote>
{
  /* */
}

var typesList = [] { typeof(OtherClass) };

var result = MagicFunctionToGetTemplateTypesForNotificationHandlerInterface(typesList)

// where result = [] { typeof(Aggregate), typeof(Quote) };

I am considering going down the road of GetType().GenericTypeArguments[0] however want to check if there is a safer way first.

I have tried searching and appreciate this could very well be a duplicate, if so please let me know and I will delete.

Upvotes: 1

Views: 83

Answers (1)

Dmitry
Dmitry

Reputation: 14059

You could try something like this:

var result = typeof(OtherClass).GetInterfaces()
    .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(INotificationHandler<>))
    .Select(x => x.GetGenericArguments()[0])
    .ToArray();

Upvotes: 1

Related Questions