views:

122

answers:

1

Hi there,

I do need a solution for loading lists of objects - lookups where only one property is referenced from the current object as in this example.

class LookupObjectAddress
{
 [...]
 public string City
 { get; set; }
 [...]
}

class WorkingObject
{
 // references the property from LookupObjectAddress
 public string City
 { get; set; }
}

For the lookup I need a List to be loaded from the database, to know from where to load the information I use an Attribute

class WorkingObject
{
 // references the property from LookupObjectAddress
 [Lookup(Type=typeof(LookupObjectAddress), staticloaderclass="LookupObjLoader", staticloaderMethod="LookupObjLoadMethod")]
 public string City
 { get; set; }
}

After reading out the PropertyInfo for the WorkingObject.City Property I know the type of the lookup object, and from which class with which method to load it. Now I need the bridge to get a List with that three parameters to work with.

Type loaderClass = Type.GetType(classname);
MethodInfo loaderMethod = loaderClass.GetMethod(loadmethod);
object objList = loaderMethod.Invoke(null, new object[] {});

Since I need the typed List<> for using properties of the LookupObjects on the UI, how can I become a useable list in Code?

My ideal Outcome would be, if I could just type:

var list = Loader.Load(type, "LookupObjLoader", "LookupObjLoadMethod");

where the parameters are read from the Attribute.

+4  A: 

In order to produce a List<T> type, and thus instance, at runtime, where T comes from a Type object (ie. not known at compile-time), you would do this:

Type genericListType = typeof(List<>); // yes, this really is legal syntax
Type elementType = ...
Type specificListType = genericListType.MakeGenericType(elementType);
// specificListType now corresponds to List<T> where T is the same type
// as elementType
IList list = (IList)Activator.CreateInstance(specificListType);

This will produce, at runtime, the correct list type and store it in the list variable.

Note that there is no way you can get the compiler to infer the variable type, so this:

var list = Loader.Load(...)

will still not produce a List<T> type, it will have to use a non-generic, known-at-compile-time type to store the list, like IList, but the object you store in it can be a generic one, produced the way I describe above.

Lasse V. Karlsen
This should do. Thanks for it.
BeowulfOF