I found this but tried to use it and failed.
How can i create an object using reflections and make it fast by putting it in a delegate?
DynamicMethod dm = new DynamicMethod("MyCtor", t, new Type[] { });
var ctor = t.GetConstructor(new Type[] { });
ILGenerator ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Newobj, ctor);
ilgen.Emit(OpCodes.Ret);
var d = (Func<T>)dm.CreateDelegate(t);
dm.Invoke(null, new object[] { });
Before putting it in a deleage i tried to at least invoke it and when i did above i get the error
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an invocation.
If i call d() instead i get the exception
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: Type must derive from Delegate.
How do i put a no param constructor into a delegate and call it?
If you have access to .NET 3.5 (which your use of
Func<T>
suggests), you may findExpression
easier thanILGenerator
:Pretty easy to extend that to use a specific constructor, passing arguments, or adding post-constructor property bindings; casts, conversions, etc (see this related answer). If you have a specific scenario, I'll happily add an example.
Note also that you should cache and re-use any such constructors - otherwise you lose the benefit (i.e. don't recreate the delegate per-call).
Generic method for constructing delegates, calling constructor directly. Automatically searches constructor in given type with signature of given delegate type and constructs delegate of that type. Code here:
is part of Yappi project's sources. Using it you can construct delegate calling any constructor of given type, including constructor with parameters (except ref and out parameters).
Sample usage:
After construction of delegate, store it somewhere in static dictionary or in static field of class with generic parameter. Don't construct new delegate each time. Use one delegate for constructing multiple instances of given type.
There are no arguments to the constructor so you should not load arguments on the stack
ilgen.Emit(OpCodes.Ldarg_0)
:Try this -