6

I am trying to dynamically create an empty constructor that takes an argument and simply calls base(argument) using TypeBuilder.

My code is something like:

(...)
// Create a class derived from this class
TypeBuilder typeBuilder = moduleBuilder.DefineType("NewClass", TypeAttributes.Class, this.GetType());    
ConstructorInfo baseCtor = this.GetType().GetConstructor(new[] { typeof(int) });

// Define new ctor taking int
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public,  CallingConventions.Standard, new[] { typeof(int) });

// Generate code to call base ctor passing int
ILGenerator ctorIL = constructorBuilder.GetILGenerator();
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_1);
ctorIL.Emit(OpCodes.Call, baseCtor);
ctorIL.Emit(OpCodes.Ret);

// Generate derived class
Type type = typeBuilder.CreateType();

// Try to instantiate using new constructor 
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
object instance = ctor.Invoke(new object[] { 42 });
(...)

but is always failing throwing an exception
System.Reflection.TargetInvocationException: NewClass..ctor(int32)
What am I doing wrong?

Many thanks in advance for any help,
Paolo

kvb
  • 54,864
  • 2
  • 91
  • 133
Paull
  • 1,020
  • 1
  • 12
  • 21
  • I'll happily look later if you don't get an answer; but: have you tried disassembling a c# example to check the opcodes? – Marc Gravell Dec 07 '11 at 17:40
  • 1
    I am able to run the provided code successfully. TargetInvocationException is what you will see if the base constructor has an error/exception. You should be able to breakpoint the base.Ctor(int) to troubleshoot further. – John Arlen Dec 07 '11 at 18:32
  • Thanks for the suggestions, I am in an environment where I'm not easily able to debug and I was assuming that the code itself was raising the exception. I'll rip the code into a minimal class and try to debug the base constructor. – Paull Dec 07 '11 at 22:48
  • Using the debugger revealed that the exception is really something like: `System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxx' failed.` – Paull Dec 15 '11 at 09:00
  • 1
    See here: http://stackoverflow.com/questions/6879279/using-typebuilder-to-create-a-pass-through-constructor-for-the-base-class – dlras2 Jan 10 '12 at 01:19

0 Answers0