Using C# Type as generic
Posted
by I Clark
on Stack Overflow
See other posts from Stack Overflow
or by I Clark
Published on 2010-06-08T04:47:51Z
Indexed on
2010/06/08
4:52 UTC
Read the original article
Hit count: 282
I'm trying to create a generic list from a specific Type that is retrieved from elsewhere:
Type listType; // Passed in to function, could be anything
var list = _service.GetAll<listType>();
However I get a build error of:
The type or namespace name 'listType' could not be found (are you missing a using directive or an assembly reference?)
Is this even possible or am I setting foot onto C# 4 Dynamic territory?
As a background: I want to automatically load all lists with data from the repository. The code below get's passed a Form Model whose properties are iterated for any IEnum (where T inherits from DomainEntity). I want to fill the list with objects of the Type the list made of from the repository.
public void LoadLists(object model)
{
foreach (var property in model.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
{
if (IsEnumerableOfNssEntities(property.PropertyType))
{
var listType = property.PropertyType.GetGenericArguments()[0];
var list = _repository.Query<listType>().ToList();
property.SetValue(model, list, null);
}
}
}
© Stack Overflow or respective owner