3

So I am currently writing code that generates objects at run time. Much like in This Q&A.

However I'm having trouble finding any information regarding dynamically creating a type with that same type embedded in it. something like:

public class Foo
{
    private Foo _Parent

    public Foo()
    {}

    public Foo Parent
    {
        get { return _Parent; }
        set { _Parent = value; }
    }
}

Is there any way to do this in c# using reflection or emit?

Thanks in advance.

Community
  • 1
  • 1
Val
  • 930
  • 6
  • 10

1 Answers1

2

Today I learned you can cast a TypeBuilder to a Type to get a handle on the type it's going to build:

TypeBuilder tb = // get from a ModuleBuilder or wherever
Type typeImAboutToBuild = (Type)tb;

FieldBuilder fb = tb.DefineField(
    "_Parent", typeImAboutToBuild, FieldAttributes.Private)

Edit: TypeBuilder actually inherits from Type, rather than this being an explicit or implicit conversion operation; you don't even need the cast:

TypeBuilder tb = //whatever
FieldBuilder fb = tb.DefineField("_Parent", tb, FieldAttributes.Private)
Community
  • 1
  • 1
Rawling
  • 49,248
  • 7
  • 89
  • 127