O'Reilly logo

Shared Source CLI Essentials by Ted Neward, Geoff Shilling, David Stutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required