Purpose of Activator.CreateInstance with example?

Tabriz Atayi picture Tabriz Atayi · Sep 29, 2011 · Viewed 156.3k times · Source

Can someone explain Activator.CreateInstance() purpose in detail?

Answer

deepee1 picture deepee1 · Sep 29, 2011

Say you have a class called MyFancyObject like this one below:

class MyFancyObject
{
 public int A { get;set;}
}

It lets you turn:

String ClassName = "MyFancyObject";

Into

MyFancyObject obj;

Using

obj = (MyFancyObject)Activator.CreateInstance("MyAssembly", ClassName))

and can then do stuff like:

obj.A = 100;

That's its purpose. It also has many other overloads such as providing a Type instead of the class name in a string. Why you would have a problem like that is a different story. Here's some people who needed it: