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.
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)
.