Search code examples
c#cilreflection.emit

Constructor chaining with Reflection.Emit / Sigil


I'm trying to create a class like the following using Sigil which is a wrapper around Reflection.Emit.

public class Test
{
    public Test(string arg1)
    {
    }

    public Test() : this("arg1") 
    {
    }
} 

Using the following Code I keep getting the Exception: "The invoked member is not supported before the type is created."

using System;
using System.Reflection;
using System.Reflection.Emit;
using Sigil.NonGeneric;

public class Program
{
    public static void Main()
    {
        var asmName = new AssemblyName("MyAssembly");
        var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Save);

        var mod = asm.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");

        var test = mod.DefineType("Test", TypeAttributes.Public);

        // special constructor
        var ctorBuilder1 = Emit.BuildConstructor(new Type[] { typeof(string) }, test, MethodAttributes.Public);
        ctorBuilder1.Return();
        var ctor1 = ctorBuilder1.CreateConstructor();

        // default constructor calling the special one
        var ctorBuilder2 = Emit.BuildConstructor(new Type[] { }, test, MethodAttributes.Public);
        ctorBuilder2.LoadArgument(0);
        ctorBuilder2.LoadConstant("arg1");
        ctorBuilder2.Call(ctor1); // Exception thrown here
        ctorBuilder2.Return();
        var ctor2 = ctorBuilder2.CreateConstructor();

        test.CreateType();
        asm.Save(asmName.Name + ".dll");
    }
}

I read about using ´DynamicMethod´ but got the Error "Delegate of type Sigil.Impl.NonGenericPlaceholderDelegate takes no parameters" when I replaced my BuildConstructor call with the following:

var piCtor = Emit.NewDynamicMethod(pi, new Type[] {}, ".ctor", mod);

Thanks for your help.


Solution

  • It looks like at the moment, at least Sigil.NonGeneric doesn't handle this properly. However, it also looks like you can mix and match Sigil with non-Sigil code.

    So you can change just your ctorBuilder2 code to use the built-in Reflection.Emit code:

    var ctorBuilder2 = test.DefineConstructor(MethodAttributes.Public,
        CallingConventions.Standard, new Type[0]);
    var generator = ctorBuilder2.GetILGenerator();
    generator.Emit(OpCodes.Ldarg_0);
    generator.Emit(OpCodes.Ldstr, "arg1");
    generator.Emit(OpCodes.Call, ctor1);
    generator.Emit(OpCodes.Ret);
    

    That then seems to build the assembly as desired.