0

I have a problem using dynamic types to instantiate a custom class. Example, I have the following class:

public class myClass<T>
{
    public myClass(String header);
}

If I use the following code, everything works fine:

var myInstance = new myClass<int>("myHeader");

However, I am in a position I don't have the int type defined, so I need to dynamically cast it from a generic type parameter. What I tried so far:

1.

    Type myType = typeof(int);
    var myInstance = new myClass<myType>("myHeader");

2.

    int myInt = 0;
    Type myType = myInt.GetType();
    var myInstance = new myClass<myType>("myHeader");

In all examples I get the following error:

The type or namespace name 'myType' could not be found (are you missing a using directive or an assembly reference?)

The reasons I cannot use int directly is because I am loading the types from specific assemblies at runtime, so they will not be "int" at all times.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
m506
  • 1
  • 2

1 Answers1

0

For creating generic lists on the runtime, you have-to use Reflection.

int myInt = 0;
Type myType = myInt.GetType();

// make a type of generic list, with the type in myType variable
Type listType = typeof(List<>).MakeGenericType(myType);

// init a new generic list
IList list = (IList) Activator.CreateInstance(listType);

Update 1:

int myInt = 0;
Type myType = myInt.GetType(); 
Type genericClass = typeof(MyClass<>); 
Type constructedClass = genericClass.MakeGenericType(myType); 
String MyParameter = "value"; 
dynamic MyInstance = Activator.CreateInstance(constructedClass, MyParameter);
Ali Bahrami
  • 5,935
  • 3
  • 34
  • 53
  • Thanks Ali, as a complement, below the full code: int myInt = 0; Type myType = myInt.GetType(); Type genericClass = typeof(MyClass<>); Type constructedClass = genericClass.MakeGenericType(myType); String MyParameter = "value"; dynamic MyInstance = Activator.CreateInstance(constructedClass, MyParameter); Regards – m506 Dec 03 '16 at 14:47
  • @m506 You're welcome. Don't forget to accept the answer if was what you were looking for. I updated the post and put your code there. – Ali Bahrami Dec 03 '16 at 18:17