How to instantiate a generic class using its type name?

In my project (.NET 3.5), I got a lot of DAO: (for each object)

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

I need to create a function that gets the name DAO or the name of its entity (whatever you think is better) and run the function "getAll ()" DAO. As this code does for only one object:

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

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

The socket is as follows:

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

Edit

One detail I forgot is how getAll () returns:

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

Therefore, I will also need to use reflection in the list. How?

Decision

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

If you use generics and do not want to implement a specific DAO for each type of entity, 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 execute Type.GetType() with the computed DAO name (assuming you follow a specific naming convention).

+6
source

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(); 
+2
source

All Articles