Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a type dynamically using reflection?

Tags:

c#

reflection

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 initialization. The base class won't know what type of object it is supposed to instantiate, but the derived class will. So, I want to have the derived class pass the type to the base class in a base() call. The code looks something like this:

public abstract class MyBaseClass
{
    protected MyBaseClass(Type myType)
    {
         // Instantiate object of type passed in 
         /* This is the part I'm trying to figure out */
    }
}

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass() : base(typeof(Whatever))
    {
    }
}

In other words, the base class is delegating to its derived type the choice of the object type to be instantiated.

Can someone please assist?

like image 414
David Veeneman Avatar asked Mar 31 '11 00:03

David Veeneman


3 Answers

Try Activator.CreateInstance(Type)

http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

like image 80
stusherwin Avatar answered Sep 22 '22 09:09

stusherwin


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)

  • http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
like image 24
JaredPar Avatar answered Sep 22 '22 09:09

JaredPar


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.

like image 18
Kirk Woll Avatar answered Sep 24 '22 09:09

Kirk Woll