Thursday, 5 March 2009

Create object from name in C# like class.forName in java

If you have a project with the assemblyName

MyCompany.MyAssemblyName

And the Class defined in some namespace. You can create an object from class name and assembly name information.

namespace MyCompany.MyAssemblyName.MyNamespace
{
  [TestFixture]
  public class Test
  {
    [Test]
    public void Test1()
    {
      MyClass obj = (MyClass)Activator.CreateInstance("MyCompany.MyAssemblyName","MyCompany.MyAssemblyName.MyNamespace.MyClass").Unwrap();
      obj.Test();
    }
  }
  public class MyClass
  {
    public void Test()
    {
      Console.WriteLine("Test");
    }
  }
}

No comments:

Post a Comment