Emitting Components Dynamically

In an interesting twist, not only does the CLI provide the facilities to examine all this structure and metadata at runtime via the System.Reflection namespace, it also provides the ability to emit entirely runtime-synthesized types via the System.Reflection.Emit namespace. This means, quite literally, that it becomes possible to build these types “on the fly,” as it were. While we won’t do a complete tutorial on System.Reflection.Emit (other sources cover this API in some detail), it does prove interesting to follow the System.Reflection.Emit calls and see how they end up in this same structure we’ve just been diving through.


What follows here is a simple Reflection.Emit program, which dynamically produces, the “Hello World” sample that every programming textbook defines. (Note that we don’t reuse the Echo sample because to emit even something as simple as Echo would occupy several pages of pure code.)

 using System; using System.Reflection; using System.Reflection.Emit; class App { static void Main( ) { AssemblyName an = new AssemblyName( ); an.Name = "HelloReflectionEmit"; AppDomain ad = AppDomain.CurrentDomain; AssemblyBuilder ab = ad.DefineDynamicAssembly(an, / AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(an.Name, "Hello.exe"); TypeBuilder tb = mb.DefineType("Hello.Emitted", TypeAttributes.Public | TypeAttributes.Class); MethodBuilder mthb = tb.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, ...

Get Shared Source CLI Essentials now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.