Joe
Joe

Reputation: 5487

Determine if class is a subclass of a type with multiple generic parameters

Given the following class hierarchy

public abstract class MyGenericClass<T1, T2> 
{
    public T1 Foo { get; set; }
    public T2 Bar { get; set; }
}

public class BobGeneric : MyGenericClass<int, string>{}
public class JimGeneric : MyGenericClass<System.Net.Cookie, System.OverflowException>{}

I would have thought that I could do the following

//All types in the assembly containing BobGeneric and JimGeneric
var allTypes = _asm.GetTypes();  

//This works for interfaces, but not here 
var specialTypes = allTypes.Where(x => typeof(MyGenericClass<,>).IsAssignableFrom(x))

//This also fails
typeof(BobGeneric).IsSubclassOf(typeof(MyGenericClass<,>)).Dump();

How would I determine in code that BobGeneric inherits from MyGenericClass?

Upvotes: 5

Views: 1293

Answers (1)

O. R. Mapper
O. R. Mapper

Reputation: 20730

You're looking for GetGenericTypeDefinition:

typeof(BobGeneric).GetGenericTypeDefinition().IsSubclassOf(typeof(MyGenericClass<,>)).Dump();

You can imagine that method as "stripping away" all generic type arguments, just leaving the raw definition with its formal generic parameters.

If it does not work directly on BobGeneric, you may have to navigate upwards in the type hierarchy till you find MyGenericClass<...,...> (or any type for which IsGenericType returns true).

Upvotes: 7

Related Questions