Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find type implementing generic interface through reflection

Tags:

c#

reflection

Consider a generic interface

public interface IA<T>
{
}

and two implementations

public class A1 : IA<string>
{}
public class A2 : IA<int>
{}

I want to write a method that finds the classes who implements IA interface with a specific type

public Type[] Find(IEnumerable<Type> types, Type type)

so that the following call

Find(new List<Type>{ typeof(A1), typeof(A2)}, typeof(string))

will return the type A1

IMPORTANT NOTE

I can assume that all the types passed in as the list will implement IA however not necessarily directly (For example A1 can inherit from BaseA that implements IA<string>)

How can I accomplish this through reflection?

like image 479
Omri Btian Avatar asked May 20 '26 09:05

Omri Btian


1 Answers

Use MakeGenericType to construct a specific generic type and check if it is available in the list of interfaces which the given class implements.

private static Type FindImplementation(IEnumerable<Type> implementations, Type expectedTypeParameter)
{
    Type genericIaType = typeof(IA<>).MakeGenericType(expectedTypeParameter);

    return implementations.FirstOrDefault(x => x.GetInterfaces().Contains(genericIaType));
}

And you call it like this

Type type = FindImplementation(new []{ typeof(A1), typeof(A2)}, typeof(string));
//Returns A1
like image 155
Sriram Sakthivel Avatar answered May 22 '26 21:05

Sriram Sakthivel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!