Generating a constructor that takes an argument and just calls the base (argument) using TypeBuilder

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

My code looks something like this:

(...)
// 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 always ignores the exception.   System.Reflection.TargetInvocationException: NewClass..ctor(int32)
What am I doing wrong?

Thanks so much for any help,
Paolo

+5
source share

All Articles