Initialize class by string variable in C #?

Is it possible to initialize a string variable class? I have some code in PHP.

<?php
  $classname = "test";

  $oTest = new $classname();

  class test{
  }
?>

how to do it in c #?

+5
source share
3 answers
System.Activator.CreateInstance(Type.GetType(className))

The problem, however, is that C # 3.0 is a statically typed language. You cannot just call random methods on the returned object. You can have classes that you could create, implement some common interface and pass the result of the above expression to the interface, or manually use reflection to call methods on the returned object.

+19
source

Activator.CreateInstance .

var instance = Activator.CreateInstance("SomeAssemblyName","Some.Full.Type.Test");
+5

You can use Activator.CreateInstance. The documentation for various overloads is here: http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

+1
source

All Articles