Is there any way to detect the type specified in a generic parameter on a class?
For example, I have the three classes below:
public class Customer
{ }
public class Repository<T>
{ }
public class CustomerRepository : Repository<Customer>
{ }
public class Program
{
public void Example()
{
var types = Assembly.GetAssembly(typeof(Repository<>)).GetTypes();
//types contains Repository, and CustomerRepository
//for CustomerRepository, I want to extract the generic (in this case, Customer)
}
}
For each of the repository objects brought back, I’d like to be able to tell what type is specified.
Is that possible?
EDIT
Thanks to @CuongLe, got this which is working, however looks messy….
(also help from resharper ;))
var types = Assembly.GetAssembly(typeof(Repository<>))
.GetTypes()
.Where(x => x.BaseType != null && x.BaseType.GetGenericArguments().FirstOrDefault() != null)
.Select(x => x.BaseType != null ? x.BaseType.GetGenericArguments().FirstOrDefault() : null)
.ToList();
Assume you now hold the type of
CustomerRepositoryby selecting from list of types:Edit: You don’t need to trust Re-Sharper 100%. Since you do
Whereto select all type whoseBaseTypeis notnull, needless to check again inSelect. For more,FirstOrDefaultactually returnnull, this code is optimized: