Home > .NET / C#, English, Programming > TypeBuilder is a Type!

TypeBuilder is a Type!

June 4th, 2009

Today, although it would have been quite obvious by simply reading the MSDN (yes, RTFM fits in this situation), I spent some minutes searching for a way to dynamically create two mutually referencing classes via TypeBuilder. What I was looking for was a way to generate something like:

class A { public B b; }
class B { public A a; }

My first attempt was to create A without any fields, use the type to generate B and modify the former afterwards. As one cannot change a type once TypeBuilder.CreateType() has been called, that attempt failed.
After some searching I found out that TypeBuilder is a subclass of Type. Knowing this, the initial problem is easily solvable through:

TypeBuilder aBuilder = moduleBuilder.DefineType(…);
TypeBuilder bBuilder = moduleBuilder.DefineType(…);
aBuilder.DefineField("b", bBuilder, FieldAttributes.Public);
bBuilder.DefineField("a", aBuilder, FieldAttributes.Public);
aBuilder.CreateType();
bBuilder.CreateType();

Once again the simplest solution was the best.

Categories: .NET / C#, English, Programming
Comments are closed.