How to tell if a class implements an interface with a generic type
I have the following code:
public interface IInput
{
}
public interface IOutput
{
}
public interface IProvider<Input, Output>
{
}
public class Input : IInput
{
}
public class Output : IOutput
{
}
public class Provider: IProvider<Input, Output>
{
}
Now I would like to know if the provider is using an IProvider using reflection? I do not know how to do that. I tried the following:
Provider test = new Provider();
var b = test.GetType().IsAssignableFrom(typeof(IProvider<IInput, IOutput>));
It returns false.
I need help. I would like to avoid using Type Name (String) in order to figure this out.
source to share
To check if it implements it at all:
var b = test.GetType().GetInterfaces().Any(
x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IProvider<,>));
To find what, use FirstOrDefault
instead Any
:
var b = test.GetType().GetInterfaces().FirstOrDefault(
x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IProvider<,>));
if(b != null)
{
var ofWhat = b.GetGenericArguments(); // [Input, Output]
// ...
}
source to share
First, IProvider
it must be declared using interfaces instead of classes in its definition:
public interface IProvider<IInput, IOutput>
{
}
Then the class definition Provider
should be:
public class Provider: IProvider<IInput, IOutput>
{
}
And finally, call IsAssignableFrom
back, it should be:
var b = typeof(IProvider<IInput, IOutput>).IsAssignableFrom(test.GetType());
source to share