• Become a Fan!
  • Follow On Twitter

Create Instance of a Class at Run Time

Posted In Tutorials - By NitiN Kumar Jain On Tuesday, October 21st, 2008 With 2 Comments

Yes, I am talking about creating instances of classes at run time in C#.

In VB days, CreateObject function used to do this thing for us:
CreateObject (DllName.ClassName) as in e.g.


CreateObject ("MessagingFramework.TransportAdaptor")

But the most easiest way to do it in C# is to use the CreateInstance method of Activator class. This class is directly available in the System namespace only.

Activator class can be used to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited.

We are interested in its basic method accepting two arguements; assembly name and type name. Another overloaded method only accepting the complete type name if the class is within the same assembly.

Activator.CreateInstance(AssemblyName, CompleteTypeName) as in e.g.


Activator.CreateInstance("MessagingFramework", "MessagingFramework.Adaptors.TransportAdaptors");

The above will creates an instance of the type whose name is specified, using the named assembly and default constructor.

But that’s not it, you would have to unwrap the handle object returned by the CreateInstance method and type cast it into its Interface object to use.


ITransportAdaptor ta = Activator.CreateInstance("MessagingFramework", "MessagingFramework.Adaptors.TransportAdaptor").Unwrap() as ITransportAdaptor ;

Above method allows objects to be created remotely without having to load the type locally.

Hope it helps!

-NKJ



Tags:
Displaying 2 Comments
Have Your Say

  1. Teju says:

    Hi

    In my application I have to create the object at runtime.

    Could you explain the role of interface class.

    My classes do have any interfaces so how to handle without interface

  2. Teju says:

    Hi

    In my application I have to create the object at runtime.

    Could you explain the role of interface class.

    My classes do have any interfaces so how to handle without interface