Emitting a Type that inherits from a base type referencing the built Type

Emitting a Type that inherits from a base type referencing the built Type

Incredibly simple, yet it took me a while to craft the correct search terms to come up with this solution.  I can’t even find that forum post now, so hopefully this entry will save someone else some time.

In a lot of solutions there exists a base class that would take the inheritor as a type reference to be able to do some work on it - you’ll typically see this pattern  in fluent interfaces and classes that use reflection.  In our current solution we generate NHibernate entities on the fly, which all need to inherit from a base class that look something like this :

public abstract class DynamicEntity : IDynamicEntity where T:DynamicEntity
{
    public virtual long Id { get; set; }
}

Utilizing TypeBuilder, we can build new classes as follows :

TypeBuilder typeBuilder = moduleBuilder.DefineType(className, TypeAttributes.Public);
Type baseType = typeof(DynamicEntity);
typeBuilder.SetParent(baseType.MakeGenericType(?)); // Add methods, properties, etc.
Type newType = typeBuilder.CreateType();

Note the question mark  (?) in the call to MakeGenericType. What do we set the base type to if the base type has to include the unconstructed type?  Turns out that the solution is incredibly simple (and I’m incredibly stupid) :  TypeBuilder inherits from System.Type, so we can reference it as a type placeholder:

typeBuilder.SetParent(baseType.MakeGenericType(typeBuilder));

Photo by Markus Spiske on Unsplash

dotnet 

See also