tags:

views:

85

answers:

2

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);
        }
    }
}
+3  A: 

You can't pass a variable as a generic type/method parameter, however you can do some simple things using reflection, for example you can construct list this way:

Type listType = typeof(int);
var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(listType));

Not sure if it will be helpful, since you'll need to cast that list to something to make it useful, and you cant simply cast it to a generic type/interface without specifying generic type parameters.

You can still add/enumerate such list by casting it to non-generic versions of interfaces ICollection, IList, IEnumerable.

max
Yeah, I thought that might be the case. I'm consuming the list from a method<T>() elsewhere in the system, so can't create the list from scratch. Thanks for your help!
I Clark
You can also call a generic method using reflection, but you'll still have the same problems with result. Check this article about dynamic generic method invocation: http://www.codeproject.com/KB/dotnet/InvokeGenericMethods.aspx
max
A: 

You need to tell it the type that listType is

var list = _repository.Query<typeof(listType)>().ToList();
dirtmike
Sorry, but it's already a Type. typeof() is used to convert the name of a class, interface, etc (i.e. as if you were going to access a static method on it).
I Clark
You are correct.
dirtmike