Use Activator.CreateInstance() to Create Objects Dynamically

You can use Activator.CreateInstance() method to create objects from String type of Assembly Name. The following code stub demonstrate how to use that method.

namespace ActivatorTest
{
public interface IActBase
{
void Execute();
}
}

namespace ActivatorTest
{
public class ActChild1 : IActBase
{
public void Execute()
{
Console.WriteLine("Activator Child 1");
}
}
}

namespace ActivatorTest
{
public class ActChild2 : IActBase
{
public void Execute()
{
Console.WriteLine("Activator Child 2");
}
}
}

namespace ActivatorTest
{
public class Program
{
static void Main(string[] args)
{
const string AssemblyName = "ActivatorTest.ActChild2";
//The AssemblyName can be loaded through the configuration based
// on your requirement. Here its hard coded.
IActBase instance = (IActBase)Activator.CreateInstance(Type.GetType(AssemblyName));
instance.Execute();
}
}
}
For More Info:- http://www.knowdotnet.com/articles/activator_createinstance.html

No comments:

Post a Comment