Create object from a class string in .net

Have you ever wanted to create an object from a string describing what class you want to instantiate from? Perhaps not, but it might come in use if you for instance want to implement some kind of plug-in system for your application or maybe toggle between different data access classes from web.config.

In this example I will show you how to create an interface that our different classes will implement. It’s necessary that they all follow the same interface when we later want to call a function in the object we’ve created.

The interface

namespace ClassFromStringTest {
public interface ICommon {
string WhoAmI();
}
}

Okay, this is pretty straightforward. Each class will implement this interface with one single function (WhoAmI) that will return a string to help us identify which class that is instantiated.

Class 1

namespace ClassFromStringTest {
class Class1 : ICommon {
public string WhoAmI() {
return "I'm Class1";
}
}
}

Class 2

namespace ClassFromStringTest {
class Class2 : ICommon {
public string WhoAmI() {
return "I'm Class2";
}
}
}

Class 3 – External!

Now we’ll do something different to really show the power of this. We’re creating a class in a new project and assembly!

Be sure to include your first project in the new one in order to be able to use the ICommon interface.

namespace ExternalNewClass {
public class MyOtherClass : ClassFromStringTest.ICommon {
public string WhoAmI() {
return "I'm an external library";
}
}
}

Testing the classes

It’s time to switch back to the first project and add a class for testing. Add a reference to your ExternalNewClass project so that you can instantiate the MyOtherClass as well.

using System;

namespace ClassFromStringTest {
class ClassTester {
public static string WhoAreYou() {
string myClassName = "ClassFromStringTest.Class1";
string retval = "";

try {
ICommon myClass = (ICommon)Activator.CreateInstance(Type.GetType(myClassName));
retval = myClass.WhoAmI();
}
catch (Exception ex) {
retval = "Error: " + ex.Message;
}
return retval;
}
}
}

You can change myClassName to any of:

  • ClassFromStringTest.Class1
  • ClassFromStringTest.Class2
  • ExternalNewClass.MyOtherClass

The magic in this is the System.Activator.CreateInstance function that creates an object from the class name you feed it with. Using Type.GetType(string) instead of the other variants of CreateInstance is that it can handle different assemblies much easier. Notice how we add the assembly name before the class name, for instance ClassFromStringTest.Class1. The returning object is then casted to our interface ICommon so that we know that we can reach it’s methods.

Hope you’ll find this useful :)


Bookmark and Share

Related posts:

Comments

comments powered by Disqus