GxFlint
GxFlint

Reputation: 294

How to instantiate a generic class by using its type name?

In my project (.NET 3.5) I got many DAOs like this: (One for every entity)

public class ProductDAO : AbstractDAO<Product> 
{...}

I need to create a function that will receive the name of the DAO or the name of its entity (whatever you think it's best) and run the DAOs "getAll()" function. Like this code does for just one entity:

ProductDAO dao = new ProductDAO();
dao.getAll();

I'm new to C#, how can I do that with reflection?

Someting like this:

String entityName = "Product";
AbstractDAO<?> dao = new AbstractDAO<entityName>()
dao.getAll();

Edit

One detail that I forgot, this is how getAll() returns:

IList<Product> products = productDao.getAll();

So I would also need to use reflection on the list. How?

Solution

Type daoType = typeof(AbstractDAO<>).Assembly.GetType("Entities.ProductDAO");
Object dao = Activator.CreateInstance(daoType);
object list = dao.GetType().GetMethod("getAll").Invoke(dao, null);

Upvotes: 4

Views: 3326

Answers (2)

jaywayco
jaywayco

Reputation: 6296

Try:

Type d1 = typeof(AbstractDAO<>);
Type[] typeArgs = {Type.GetType("ProductDAO")};
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);

o.GetType().GetMethod("getAll").Invoke();

Upvotes: 3

Lucero
Lucero

Reputation: 60190

If you are using generics and don't want to implement a specific DAO for each entity type, you can use this:

Type entityType = typeof(Product); // you can look up the type name by string if you like as well, using `Type.GetType()`
Type abstractDAOType = typeof(AbstractDAO<>).MakeGenericType(entityType);
dynamic dao = Activator.CreateInstance(abstractDAOType); 
dao.getAll();

Otherwise, just do a Type.GetType() with the computed name of the DAO (assuming that you follow a certain convention for the names).

Upvotes: 8

Related Questions