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.

+3


source to share


3 answers


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]
    // ...
}

      

+4


source


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());

      

0


source


I was able to achieve this using Mark's suggestion.

Here's the code:

(type.IsGenericType &&
                (type.GetGenericTypeDefinition() == (typeof(IProvider<,>)).GetGenericTypeDefinition()))

      

-1


source







All Articles