Creating Code at runtime with C#
Reflection can be used to create code at runtime. It includes namespace called System.Reflection.Emit that houses set of builder classes that take care of creating code. The process is just like normal process. We create an assembly following by a module within the assembly, and finally types within the module.
Builder Classes
Name | Description for Used to Buid |
---|---|
AssemblyBuilder | Assemblies at runtime |
ConstructorBuilder | Constructors at runtime |
EnumBuilder | Enumerations at runtime |
EventBulder | EventBulder |
FieldBuilder | Fields at runtime |
LocalBuilder | Local variables |
MethodBuilder | Methods at runtime |
ModuleBuilder | Modules at runtime |
ParameterBuilder | Method parameters at runtime |
PropertyBuilder | Properties at runtime |
TypeBuilder | Types at runtime |
AssemblyName myTempName = new AssemblyName();
myTempName.Name = "MyTempAssembly";
AssemblyBuilder myAssemBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(tempName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder modBldr = myAssemBldr.DefineDynamicModule("MainMod", "MyTempAssembly.dll");
TypeBuilder typeBldr = modBldr.DefineType("MyNewType", TypeAttributes.Public | TypeAttributes.Class);
TypeBuilder Definitions
Name | Description |
---|---|
DefineConstructor | Constructors |
DefineDefaultConstructor | Parameterless constructor |
DefineEvent | Events |
DefineField | Fields |
DefineGenericParameters | Generic parameters |
DefineMethod | Methods |
DefineMethodOverride | Overloads for methods |
DefineNestedType | New types |
DefinePInvokeMethod | Calls to external code |
DefineProperty | Properties |
Creating Code at runtime