Click here to Skip to main content
15,881,559 members
Articles / Programming Languages / C#
Tip/Trick

Alternative to Activator.CreateInstance

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
25 Jan 2012CPOL 58.1K   15   9
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer BBD Johannesburg
South Africa South Africa
Bsc (Hons) Business Information Systems.
MCTS: Web Applications Development with Microsoft .NET Framework 4
MCTS: Windows Communication Foundation Development with Microsoft .NET Framework 4
MCTS: Accessing Data with Microsoft .NET Framework 4
Microsoft Certified Professional Developer Certification.

Comments and Discussions

 
QuestionWorth noting... Pin
Cryptonite13-Mar-15 13:35
Cryptonite13-Mar-15 13:35 
QuestionActivator.CreateInstance() is faster than this Pin
sobo1231-Jan-14 10:43
sobo1231-Jan-14 10:43 
This is almost twice as slow as Activator.CreateInstance()
GeneralRe: Ignore that, nm...that would only apply to a public construc... Pin
Andrew Rissing26-Jan-12 3:37
Andrew Rissing26-Jan-12 3:37 
GeneralRe: Good reply, I agree in this case I'd use a "static" function... Pin
johannesnestler26-Jan-12 11:52
johannesnestler26-Jan-12 11:52 
GeneralRe: Btw, you might want to add a default constructor constraint ... Pin
Andrew Rissing25-Jan-12 15:49
Andrew Rissing25-Jan-12 15:49 
GeneralRe: I would disagree with statics being considered a bad practic... Pin
Andrew Rissing25-Jan-12 9:19
Andrew Rissing25-Jan-12 9:19 
GeneralI don't see any problem with statics. If it is for performan... Pin
Paulo Zemek25-Jan-12 9:55
mvaPaulo Zemek25-Jan-12 9:55 
GeneralBtw, you can mark these as all static. Pin
Andrew Rissing25-Jan-12 7:40
Andrew Rissing25-Jan-12 7:40 
GeneralRe: Its actually considered to be bad practice to have static me... Pin
Dean Oliver25-Jan-12 8:40
Dean Oliver25-Jan-12 8:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.