Generics and Activator.CreateInstance One-Liner

Here's a quick little one-liner I use all the time.

It will create a concrete instance that implements 'I' interface. This has a string as a parameter, but there are lots of other possibilities (and overloads for Type and CreateInstance).

But, be careful with this, you can easily get into trouble, as the magic happens at runtime, so watch your speeling.

public class Activator<I>
    {
        public static I Create(string s)
        {
            return (I)System.Activator.CreateInstance(Type.GetType(s));
        }
    }

About Brian


Brian Canzanella brings you nifty tips and tricks for most things .NET. read more...

Readers / Stuff