65.9K
CodeProject is changing. Read more.
Home

Alternative to Activator.CreateInstance

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jan 26, 2012

CPOL
viewsIcon

17692

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:

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