SexyMF
SexyMF

Reputation: 11185

How to get type of inherited generic

I have these classes:

public abstract class BaseClass{}
public class CustomerService : BaseClass<Customer>{}
public class ProductService : BaseClass<Product>{}
public class UserService : BaseClass<User>{}

at run time I have this type: entity.GetType() which will return the generic type: Customer for example.

How can I get the type of CustomerService if I have Customer type at runtime?
They are all in the same namespace.
Thanks

Upvotes: 1

Views: 140

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503140

If you're just looking for a class whose direct base type is the relevant BaseClass<T>, you can use code like this:

var targetBaseType = typeof(BaseClass<>).MakeGenericType(entityType);
var type = typeof(BaseClass<>).Assembly.GetTypes()
                              .Single(t => t.BaseType == targetBaseType);

To avoid a linear search each time, you might want to create a Dictionary<Type, Type> where the key is the entity type, and the value is the service type. You could either set that up with reflection, or just create it manually. Then it's really simple:

var type = serviceTypeDictionary[entityType];

Upvotes: 3

Related Questions