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:

PHP

    $classname = "test";

$oTest = new $classname();

class test{ ... }
?>

C#
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
typeObj.InvokeMember("Run",
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:
http://www.csharp-examples.net/reflection-examples/

Leave A Reply

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