I need to instatiate a C# type dynamically, using reflection. Here is my scenario: I am writing a base class, which will need to instantiate a certain object as a part of its in
You might want to use generics instead:
public abstract class MyBaseClass<T> where T : new()
{
protected MyBaseClass()
{
T myObj = new T();
// Instantiate object of type passed in
/* This is the part I'm trying to figure out */
}
}
public class MyDerivedClass : MyBaseClass<Whatever>
{
public MyDerivedClass()
{
}
}
The where T : new()
is required to support the new T()
construct.
Try Activator.CreateInstance(Type)
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx
You're looking for Activator.CreateInstance
object instance = Activator.CreateInstance(myType);
There are are various overloads of this method that can take constructor arguments or other information to find the type (such as names in string form)