First you need to get the type through reflection, and then you can create it with the Activator
.
To get the type, first figure out what assembly it lives in. For the current assembly where your code is running, see Assembly.GetExecutingAssembly()
. For all assemblies loaded in your current AppDomain, see AppDomain.CurrentDomain.GetAssemblies()
. Otherwise, see Assembly.LoadFrom
.
Then, if you have a class name but no namespace, you can enumerate the types in your assembly through Assembly.GetTypes()
.
Finally, create the type with Activator.CreateInstance
.
using System;
using System.Linq;
using System.Reflection;
namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
Assembly thisAssembly = Assembly.GetExecutingAssembly();
Type typeToCreate = thisAssembly.GetTypes().Where(t => t.Name == "Program").First();
object myProgram = Activator.CreateInstance(typeToCreate);
Console.WriteLine(myProgram.ToString());
}
}
}