CHAPTER 18 UNDERSTANDING CIL AND THE ROLE OF DYNAMIC ASSEMBLIES
Note As you can see, CIL supports code comments using the double-slash syntax (as well as the /*...*/ syntax,
for that matter). As in C#, code comments are completely ignored by the CIL compiler.
Now that you have the basics of CIL directives, attributes, and opcodes, let’s see a practical use of
CIL programming, beginning with the topic of round-trip engineering.
Understanding Round-Trip Engineering
You are aware of how to use ildasm.exe to view the CIL code generated by the C# compiler (see Chapter
1). What you might not know, however, is that ildasm.exe allows you to dump the CIL contained within
an assembly loaded into ildasm.exe to an external file. Once you have the CIL code at your disposal, you
are free to edit and recompile the code base using the CIL compiler, ilasm.exe.
Note Also recall that reflector.exe can be used to view the CIL code of a given assembly, as well as to
translate the CIL code into an approximate C# code base.
Formally speaking, this technique is termed round-trip engineering, and it can be useful under a
number of circumstances, such as the following:
•
You need to modify an assembly for which you no longer have the source code.
•
You are working with a less-than-perfect .NET language compiler that has emitted
ineffective (or flat-out incorrect) CIL code, and you wish to modify the code base.
•
You are constructing a COM interoperability library and wish to account for some
COM IDL attributes that have been lost during the conversion process (such as the
COM [helpstring] attribute).
To illustrate the process of round-tripping, begin by creating a new C# code file (HelloProgram.cs)
using a simple text editor, and define the following class type (you are free to create a new Console
Application project using Visual Studio if you wish. However, be sure to delete the AssemblyInfo.cs file
to decrease the amount of generated CIL code):
// A simple C# console app.
using System;
// Note that we are not wrapping our class in a namespace,
// to help simplify the generated CIL code.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello CIL code!");
Console.ReadLine();
656