Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Alternative to Activator.CreateInstance

0.00/5 (No votes)
26 Jan 2012 1  
The final solution after much debate and optimization:public class DynamicInitializer { static readonly Dictionary> list = new Dictionary>(); public static T New() where T : class { return New(typeof...

The final solution after much debate and optimization:


C#
public class DynamicInitializer
    {
        static readonly Dictionary<string, Func<object>> list = new Dictionary<string, Func<object>>();

        public static T New<T>() where T : class 
        {
            return New(typeof (T)) as T;
        }

        public static object New(Type type)
        {
            if (list.ContainsKey(type.Name)) return list[type.Name];

            Func<object> method = Expression.Lambda<Func<object>>(Expression.Block(type, new Expression[] { Expression.New(type) })).Compile();
            list.Add(type.Name, method);
            return method();
        }
    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here