Creating New Types at Runtime

The System.Reflection.Emit namespace contains classes that can create entirely new types at runtime. These classes can define a dynamic assembly in memory, define a dynamic module in the assembly, define a new type in the module, including all its members, and emit the MSIL opcodes needed to implement the application logic in the members.

Here is an example that creates and uses a new type called HelloWorld with a member called SayHello:

using System; using System.Reflection; using System.Reflection.Emit; public class Test { static void Main() { // Create a dynamic assembly in the current AppDomain AppDomain ad = AppDomain.CurrentDomain; AssemblyName an = new AssemblyName(); an.Name = "DynAssembly"; AssemblyBuilder ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); // Create a module in the assembly & a type in the module ModuleBuilder modb = ab.DefineDynamicModule("DynModule"); TypeBuilder tb = modb.DefineType("AgentSmith", TypeAttributes.Public); // Add a SayHello member to the type MethodBuilder mb = tb.DefineMethod("SayHello", MethodAttributes.Public, null, null); // Generate the MSIL for the SayHello Member ILGenerator ilg = mb.GetILGenerator(); ilg.EmitWriteLine("Never send a human to do a machine's job."); ilg.Emit(OpCodes.Ret); // Finalize the type so we can create it tb.CreateType(); // Create an instance of the new type Type t = ab.GetType("AgentSmith"); object o = Activator.CreateInstance(t); // Prints "Never send a human to do a ...

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.