Simple but Elegant, Creating a class from String

Creating a class from a string might be crucial for some very dynamic projects. It’s a single line of code that I wanted to share but I think it has a lot of power.

Simply get the executing assembly and call the GetType method. If your assembly is one of the linked assembly or even a dynamically loaded assembly, you might need to call GetReferencedAssemblies() method as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace reflectme
{
    using System;
    public class hello
    {
        public hello()
        {
            Console.WriteLine("hello");
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello");
            t.GetConstructor(System.Type.EmptyTypes).Invoke(null);
        }
    }
}

Bear in mind it will be extremely slow. Don’t do that :)