I want to create a generic List<> whose type is declared at runtime.
I can do the following, but since it's dynamic, I suspect there is a speed penalty. I'm writing a wrapper to an exotic database, so speed is critical.
List<dynamic> gdb = new List<dynamic>()
I read this post in dynamic generic types, but can't get it to work. Specifically, the object is not appearing as a List and hence has no add method.
Type ac;
switch (trail[dataPos].Type)
{
case GlobalsSubscriptTypes.Int32:
ac = typeof(System.Int32);
break;
case GlobalsSubscriptTypes.Int64:
ac = typeof(System.Int64);
break;
default:
ac = typeof(System.String);
break;
}
var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(ac);
var gdb = Activator.CreateInstance(specificListType);
How do I get gdb to appear as one of the following:
List<System.Int32>
List<System.Int64>
List<System.String>
List<object>in that case. If the type isn't known at compile time then the compile time checking that generics give you won't be of any help to you.Listbe typed won't do you any good if you don't know the type at compile time. You won't be able to cast the result to a typed list, you won't know the types that you can or can't add at compile time, and you won't know anything about what the objects in the list can do, so you can't do anything useful with the items when you take them out.List<dynamic> dandList<object> o. Then proceed to assignint i = d[0];andint j = (int)o[0];if the lists containints thenjassignment is certainly faster, if the lists contain something implicitly convertible to ints 'j' assignment would not work at all and 'i' would.