Create code at runtime with Reflection in .NET C#: Type
October 22, 2014 Leave a comment
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.