public static Func <object> CreateConstructor(Type valueType) { return(TypeExtension.CreateDefaultConstructor(valueType)); #pragma warning disable 162 var dynamicMethod = new DynamicMethod( "Create" + valueType.FullName, typeof(object), Type.EmptyTypes, Module) { InitLocals = true }; var generator = dynamicMethod.GetILGenerator(); if (valueType.IsValueType) { generator.DeclareLocal(valueType); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Box, valueType); } else { var constructor = valueType.GetDefaultConstructor(); if (constructor == null) { // throw new ArgumentException($"Type \"{valueType}\" hasn't default constructor."); } else { generator.Emit(OpCodes.Newobj, constructor); } } generator.Emit(OpCodes.Ret); return((Func <object>)dynamicMethod.CreateDelegate(CreaterType)); #pragma warning restore 162 }