Create code at runtime with Reflection in .NET C#: Type

In the previous post we looked at how to create an Assembly and a Module in code. We ended up with a ModuleBuilder object as follows:

ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyPluginModule", assemblyFileName);

We can use the ModuleBuilder to define a Type. Example:

TypeBuilder simpleType = moduleBuilder.DefineType("PluginSimpleType", TypeAttributes.Class | TypeAttributes.Public);

“PluginSimpleType” will be the name of the type. We also declare that it will be a public class. The TypeAttributes enumeration allows you to define the properties of the Type such as abstract, interface, sealed, private etc.

It is also possible to indicate that the Type derives from a base class and/or it implements one or more interfaces:

TypeBuilder extendedType = moduleBuilder.DefineType("PluginExtendedType", TypeAttributes.Class | TypeAttributes.Public, typeof(Customer), new Type[] {typeof(IEqualityComparer), typeof(IEquatable<int>) });

extendedType derives from a class called Customer and implements IEqualityComparer and IEquatable of int.

View all posts on Reflection here.

Unknown's avatarAbout Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.