Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define two types referencing each other using IL Emit

Tags:

I need to define something like this using reflection Emit:

public class Foo {
    public Bar Bar { get; set; }
}

public class Bar {
    public Foo Foo { get; set; }
}

The difficulty is that when calling TypeBuilder.DefineProperty(), I need to pass the System.Type of the property's return value, which doesn't exist yet. If the reference only went one way, it would be easy, but going both ways causes a chicken and egg problem.

I was hoping to find an overload that takes a TypeBuilder instead of a Type, which would let me define both classes at the same time and then call TypeBuilder.CreateType() on both at then end. But I'm not seeing such thing.

What is the right way to solve this?

like image 376
David Ebbo Avatar asked Feb 01 '10 03:02

David Ebbo


1 Answers

TypeBuilder is a subclass of Type: MSDN

You can pass it in to DefineProperty.

like image 91
Kennet Belenky Avatar answered Oct 12 '22 08:10

Kennet Belenky