Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 365
GxFlint Avatar asked Dec 21 '22 11:12

GxFlint


1 Answers

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).

like image 182
Lucero Avatar answered Dec 24 '22 02:12

Lucero