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)
25 Jan 2012 1  
An alternative to Activator.CreateInstance

I found that the quickest way to instantiate an object with a default constructor through Reflection is by using the DynamicMethod class. Below is a helper class I wrote to easily instantiate an object using Reflection.


C#
public class DynamicInitializer
  {
      public static V NewInstance<V>() where V : class
      {
          return ObjectGenerator(typeof(V)) as V;
      }

      private static object ObjectGenerator(Type type)
      {
          var target = type.GetConstructor(Type.EmptyTypes);
          var dynamic = new DynamicMethod(string.Empty,
                        type,
                        new Type[0],
                        target.DeclaringType);
          var il = dynamic.GetILGenerator();
          il.DeclareLocal(target.DeclaringType);
          il.Emit(OpCodes.Newobj, target);
          il.Emit(OpCodes.Stloc_0);
          il.Emit(OpCodes.Ldloc_0);
          il.Emit(OpCodes.Ret);

          var method = (Func<object>)dynamic.CreateDelegate(typeof(Func<object>));
          return method();
      }

      public static object NewInstance(Type type)
      {
          return ObjectGenerator(type);
      }
  }

You can call NewInstance using two methods: NewInstance<V>(), NewInstance(Type type).

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