Baral
Baral

Reputation: 3141

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 Provider Implements IProvider using reflection? I don't know how to do this. I tried the following:

Provider test = new Provider();
var b = test.GetType().IsAssignableFrom(typeof(IProvider<IInput, IOutput>));

It returns false..

I need help with this. I would like to avoid using Type Name (String) to figure this out.

Upvotes: 3

Views: 88

Answers (3)

Baral
Baral

Reputation: 3141

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

Here's the code:

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

Upvotes: -1

Ismail Hawayel
Ismail Hawayel

Reputation: 2453

First the IProvider should be declared using interfaces not classes in its definition :

public interface IProvider<IInput, IOutput>
{

}

Then Provider class definition should be:

public class Provider: IProvider<IInput, IOutput>
{

}

And finally the call to IsAssignableFrom is backwards, it should be:

var b = typeof(IProvider<IInput, IOutput>).IsAssignableFrom(test.GetType());

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063884

To test if it implements it at all:

var b = test.GetType().GetInterfaces().Any(
    x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IProvider<,>));

To find of what, use FirstOrDefault instead of Any:

var b = test.GetType().GetInterfaces().FirstOrDefault(
    x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IProvider<,>));
if(b != null)
{
    var ofWhat = b.GetGenericArguments(); // [Input, Output]
    // ...
}

Upvotes: 4

Related Questions