I’m generating new type at runtime,
After I’ve generated default constructor I want to generate another one, with parameters.I’m doing it this way :
cb = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
CallingConventions.Standard, new Type[] { typeof(bool) });
GenConstructorWithParameters(cb, fields, genFields);
The problem is, that I am unable to call default constructor from method GenConstructorWithParameters, because CLR does not allow me to write something like this :
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Call, cb.DeclaringType.GetConstructor(Type.EmptyTypes));//Not allowed to call .GetConstructor() on not created type!
How do I emit call to default constructor? Is it possible at all?
tb – instance of TypeBuilder, cb – ConstructorBuilder
Rather than using
DeclaringType.GetConstructor, you should pass your currentConstructorBuilderfor the default constructor.Basically, whilst building up a type, in places where you might use reflection based methods on existing types, you should instead pass in the builders that you’re already working with.
So it would be:
where
defaultCBwas theConstructorBuilderyou declared when defining the default constructor.