Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deciding on type in the runtime and applying it in generic type - how can I do this? [duplicate]

Tags:

c#

types

I would like to create a strongly type list and decide the type in runtime. This is my code.I thought it should work, but it doesn't :)

        Type elementType = Type.GetType(parts[0].Trim(),false,true);
        var elementsBeingSet = new List<elementType>();

would you have any ideat how to create a strongly typed list whose type I will decide in runtime ?

Duplicate: here are other versions:

  • Is it impossible to use Generics dynamically?
  • Declare a generic type instance dynamically
  • Calling generic method with a type argument known only at execution time
like image 847
Tomas Pajonk Avatar asked Nov 28 '08 17:11

Tomas Pajonk


1 Answers

Use Type.MakeGenericType(type[]):

Type elementType = GetElementType(); // get this type at runtime
Type listType = typeof(List<>);
Type combinedType = listType.MakeGenericType(elementType);
IList elements = (IList) Activator.CreateInstance(combinedType);

You have to use IList to keep the result - because you don't know the actual type that will be used at runtime.

For generic types with more than one type parameter you would use something like Dictionary<,>.

See also http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx

like image 148
configurator Avatar answered Oct 19 '22 10:10

configurator