Search code examples
c#reflectionreflection.emittypebuilder

Generate constructor that takes itself in constructor with TypeBuilder


I've recently started playing around with Typebuilder and I am looking to create a constructor that takes the type I am currently builder.

In code you can just write something like:

public class Foo 
{
    public Foo(Foo fooToCopy) 
    {
        // Do copy code here
    }
}

I can't think of a way to be able to reference the type being built while it is being built. I've tried creating the type prematurely to be able to reference it when specifying the constructor, but I'm not able to keep editing the type once it's been constructed.

Is there some way I can accomplish this using TypeBuilder?


Solution

  • TypeBuilder inherits Type, so anywhere you want to reference the type under construction you can supply the builder itself:

    var ctor = typeBuilder.DefineConstructor(
      MethodAttributes.Public,
      CallingConventions.Standard, 
      new Type[] { typeBuilder }
    );