Instantiating a class of type x at runtime
-
Hi, I cannot find how to create a class at runtime... if I know the type of the object, and need to create an instance.. foo myObject = new foo(); Type t = myObject.GetType(); // how do I create a new object of type t ??
-
Hi, I cannot find how to create a class at runtime... if I know the type of the object, and need to create an instance.. foo myObject = new foo(); Type t = myObject.GetType(); // how do I create a new object of type t ??
The way i tend to do it is to get the constructor (usually the parameterless one) and call invoke on it using reflection..
Type t = .... ConstructorInfo constructor = t.GetConstructor(System.Type.EmptyTypes); object newObject = constructor.Invoke(null);
----------------------------------------------------------------------- Shaun Austin: .NET Specialist. Spreading the word of .NET to the world... well the UK... well my tiny corner of it!! :-D