Maxim Tkachenko
Maxim Tkachenko

Reputation: 5808

Get type of generic parameter from class which is inherited from generic interface

I have this interface and its implementation:

public interface IInterface<TParam>
{
    void Execute(TParam param);
}

public class Impl : IInterface<int>
{
    public void Execute(int param)
    {
        ...
    }
}

How to get TParam (int here) type using reflection from typeof(Impl)?

Upvotes: 4

Views: 1638

Answers (1)

krivtom
krivtom

Reputation: 24916

You can use a bit of reflection:

// your type
var type = typeof(Impl);
// find specific interface on your type
var interfaceType = type.GetInterfaces()
    .Where(x=>x.GetGenericTypeDefinition() == typeof(IInterface<>))
    .First();
// get generic arguments of your interface
var genericArguments = interfaceType.GetGenericArguments();
// take the first argument
var firstGenericArgument = genericArguments.First();
// print the result (System.Int32) in your case
Console.WriteLine(firstGenericArgument);

Upvotes: 6

Related Questions