-2

How to create an object of class from his string name in C#/NET in Windows Phone application?

For example in PHP:

$a = 'MainClass';
$b = new $a();

Can I do this in C#/.NET for Windows Phone application?

iJoy
  • 87
  • 10
  • [this](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) is what you're looking for – Doan Cuong Jul 16 '13 at 07:51
  • This [post](http://stackoverflow.com/questions/223952/c-sharp-create-an-instance-of-a-class-from-a-string) may have answered your question. – Dong Jul 16 '13 at 07:56

2 Answers2

2

Try this (providing MainClass has a default constructor):

  // Depending on where you call it, it may require full class name: "MyNameSpace.MainClass"
  var b = Activator.CreateInstance(Type.GetType("MainClass"));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0
var obj = (MyType)Activator.CreateInstance("MyTypeAssembly", "MyType"))
Dzmitry Martavoi
  • 6,867
  • 6
  • 38
  • 59