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));
        }
    }

Tags:
brian's picture
!

thanks, I'm glad it was useful for you!

Submitted by brian on Thu, 02/03/2011 - 12:13pm.
nice one liner

brian,

timely find on this one as i'd been going mad trying to find a way to instantiate a class based on an interface.

thank you..

Submitted by jim tollan (not verified) on Thu, 02/03/2011 - 9:28am.

About Brian


profile for bluevoodoo1 on Stack Exchange, a network of free, community-driven Q&A sites

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

Readers / Stuff