This article shows how one can create and use objects on the fly through reflection in .Net. I will create a class which looks like this:

public class DynamicClass
{
    public void Show()
    {
        Console.WriteLine("Success!");
    }

}

The goal is to reflect the class at runtime, simulating getting the class type in a  string and then using the reflected instantiated object. The below code will do that.

using System.Reflection;

...

// This is the full namespaced path to my class
string targetType = "ConsoleApplication1.Test_Classes.DynamicClass";

Type reflectedType = Type.GetType(targetType);

object obj = Activator.CreateInstance(reflectedType);

DynamicClass theClass = obj as DynamicClass;

if (theClass != null)
{
    theClass.Show();
}
else
    Console.WriteLine("Failed!");

Here is the rundown of what happened

  • Line 1 : Include the reflection namespace for this magic to work.
  • Line 6 : Simulates getting the name of the object dynamically. This is the fully qualified path.
  • Line 8 : Convert the string name to an object Type.
  • Line 10 : Actually create the instance. Since our object did not have any constructor arguments or job is easier.
  • Line 12 : Do we really have a new instance of the class?
  • Line 14 : Check if it is not null. If it is not, call show which in this case will tell us it worked!
  • Line 19 : Something is wrong and the class was not created if this is hit.

Now we have the class and can operate on it as if we new’ed it up. If one has trouble determining the proper name or arguments try this trick:

Type DCType = typeof(DynamicClass);
string targetType = DCType.ToString();

// Prints out "Name: ConsoleApplication1.Test_Classes.DynamicClass"
Console.WriteLine("Name: {0}{1}", targetType, Environment.NewLine);

That works well for working with generics which have there own specifications one has to deal with generic types such as dictionary:

Dictionary<string,string> myDict = new Dictionary<string,string>();

// Prints out:
// Name: System.Collections.Generic.Dictionary`2[System.String,System.String]
Console.WriteLine("Name: {0}{1}",
   myDict.GetType().ToString(),
   Environment.NewLine);
Share