jjf1978 jjf1978 - 1 year ago 87
C# Question

IEnumerable of variable type

In the below example I have a method called GetList that takes a single string parameter and returns a List entities. I capture this in a generic IEnumerable variable because at runtime I have no idea what entity the user may want. How can I use the actual type instead of object?

I want to replace this...

IEnumerable<object> data = GetList(entityName);

With this...

IEnumerable<Company> data = GetList(entityName);

The only way I can think of handling it right now which I'm NOT going to do because we have 300+ entities is something like

case "Company":
IEnumerable<Company> data = GetList(entityName);

case "Employee":
IEnumerable<Employee> data = GetList(entityName);


Answer Source

You can't use such type in complied code - so there is really no way to create it without reflection.

Closest you can get to what you seem to want is IEnumerable<dynamic> so you can access property of object based on they run-time type.

If you just need to create strongly typed enumerable to return to some other code expecting better than IEnumerable<object> you can use reflection to create such type (Create generic List<T> with reflection).

You may also be able to have generic function that accesses result in strongly typed manner but instead of calling it directly call it via reflection after using MakeGenericMethod with correct type (How do I use reflection to call a generic method?).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download