I’m currently messing about with generics and I’m trying to write a function that I can call to load everything from a database table simply by specifying the table name.
I’m most of the way there; my generic methods all seem to work, but I’m not quite sure how to cast my results into something usable.
This is the guts of the method so far:
private static List<EntityCodeBase> GetCodeLoadResults(CodeTables table)
{
List<EntityCodeBase> results = new List<EntityCodeBase>();
Assembly assm = Assembly.Load(new System.Reflection.AssemblyName("RR"));
Type tableType = assm.GetTypes().Where(u => u.Name.ToLower() == table.ToString().ToLower()).FirstOrDefault();
MethodInfo mi = typeof(SpecificEntity).GetMethod("LoadAll");
mi = mi.MakeGenericMethod(tableType);
mi.Invoke(null, null); //how can I cast the resulting object into a List<EntityCodeBase> ?
return results;
}
Assuming
SpecificEntity.LoadAllreturns a list of some type derived fromEntityCodeBase, you can’t cast directly to aList<EntityCodeBase>but you can cast toIEnumerable<EntityCodeBase>. Then you can create a new list:It might be cleaner however, if you can get the table name from the entity type, either directly by name, using attributes, or using a map. Then you can make
GetCodeLoadResultsgeneric in the result type e.g.If you’re not using .Net 4, you can’t cast a
List<TDerived>to anIEnumerable<TBase>, so you’ll have to cast toIEnumerablefirst: