Initialise a class from string variable in C#

Ever wonder if it is possible initialise a class from a string in C#? Although it is not as simple as in PHP but it’s possible:


    $classname = "test";

$oTest = new $classname();

class test{ ... }

The class

namespace CSharpApp
public class Test
public void Run() { ... }

The code

string oName = "CSharpApp.Test";
// To create an instance
Type typeObj = Type.GetType(oName);
object instanceObj = Activator.CreateInstance(typeObj);
// To call a method from the class
BindingFlags.InvokeMethod BindingFlags.Instance BindingFlags.Public,
null, instMerchant, null);

A very good explaination and examples, such as calling different types of methods in the class, can be found here:

Spread the word. Share this post!

Leave A Reply

Your email address will not be published. Required fields are marked *