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.

The API

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 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.