0

I have the following code

 private static void Main(string[] args)
    {
        ClassC<ClassD> objC=new ClassC<ClassD>();
        var tTypeName = "MyProject.ClassD";
        ClassC<Type.GetType(tTypeName)>=new ClassC<Type.GetType(tTypeName)>();
    }
}

public class ClassC<T>
{
    ///some code here
}

public class ClassD
{
    ///some code here
}

I will instantiate classc if I know the type T is ClassD like this

 ClassC<ClassD> objC=new ClassC<ClassD>();

What if I know it during runtime, how can I pass ClassD type name to classc. I tried the following, it throw compilation error, Please advice.

var tTypeName = "MyProject.ClassD";
ClassC<Type.GetType(tTypeName)>=new ClassC<Type.GetType(tTypeName)>
Esen
  • 973
  • 1
  • 21
  • 47
  • 1
    You would have to use `Activator` and Reflection when resolving types at runtime. – Dai Jul 01 '15 at 16:32
  • Thank you @hatchet I was searching for an answer and didn't get into this thread until now. This helps me resolve my issue. – Esen Jul 01 '15 at 16:39

1 Answers1

0

You can do this with reflection. Something like...

var myType = typeof(ClassC<>).MakeGenericType(new Type[] {typeof(ClassD)});
var constructor = myType.GetConstructor(new Type[0]);
object instance = constructor.Invoke(new object[0]);
geoff_h
  • 1,245
  • 8
  • 13