Reputation: 5808
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
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