Getting type arguments of generic interfaces that a class implements

18,005

Solution 1

To limit it to just a specific flavor of generic interface you need to get the generic type definition and compare to the "open" interface (IGeneric<> - note no "T" specified):

List<Type> genTypes = new List<Type>();
foreach(Type intType in t.GetInterfaces()) {
    if(intType.IsGenericType && intType.GetGenericTypeDefinition()
        == typeof(IGeneric<>)) {
        genTypes.Add(intType.GetGenericArguments()[0]);
    }
}
// now look at genTypes

Or as LINQ query-syntax:

Type[] typeArgs = (
    from iType in typeof(MyClass).GetInterfaces()
    where iType.IsGenericType
      && iType.GetGenericTypeDefinition() == typeof(IGeneric<>)
    select iType.GetGenericArguments()[0]).ToArray();

Solution 2

typeof(MyClass)
    .GetInterfaces()
    .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IGeneric<>))
    .SelectMany(i => i.GetGenericArguments())
    .ToArray();

Solution 3

  Type t = typeof(MyClass);
            List<Type> Gtypes = new List<Type>();
            foreach (Type it in t.GetInterfaces())
            {
                if ( it.IsGenericType && it.GetGenericTypeDefinition() == typeof(IGeneric<>))
                    Gtypes.AddRange(it.GetGenericArguments());
            }


 public class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { }

    public interface IGeneric<T>{}

    public interface IDontWantThis<T>{}

    public class Employee{ }

    public class Company{ }

    public class EvilType{ }
Share:
18,005
Serhat Ozgel
Author by

Serhat Ozgel

Software developer and consultant. Areas of expertise: Web application and api development, software development, cloud architecture, mobile application backend development, e-commerce software development and integration.

Updated on June 25, 2022

Comments

  • Serhat Ozgel
    Serhat Ozgel almost 2 years

    I have a generic interface, say IGeneric. For a given type, I want to find the generic arguments which a class imlements via IGeneric.

    It is more clear in this example:

    Class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { ... }
    
    Type t = typeof(MyClass);
    Type[] typeArgs = GetTypeArgsOfInterfacesOf(t);
    
    // At this point, typeArgs must be equal to { typeof(Employee), typeof(Company) }
    

    What is the implementation of GetTypeArgsOfInterfacesOf(Type t)?

    Note: It may be assumed that GetTypeArgsOfInterfacesOf method is written specifically for IGeneric.

    Edit: Please note that I am specifically asking how to filter out IGeneric interface from all the interfaces that MyClass implements.

    Related: Finding out if a type implements a generic interface