Reputation: 199
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
switch(entitName)
{
case "Company":
IEnumerable<Company> data = GetList(entityName);
break;
case "Employee":
IEnumerable<Employee> data = GetList(entityName);
break;
...
}
Upvotes: 1
Views: 3901
Reputation: 100527
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?).
Upvotes: 3
Reputation: 19486
You can make GetList()
generic:
IEnumerable<Company> data = GetList<Company>(entityName);
IEnumerable<T> GetList<T>(string entityName)
{
List<T> list = new List<T>();
// Populate list here
return list;
}
Upvotes: 0