22.4. Generating Dynamic IL Using Reflection Emit

In Java it is possible to generate source code dynamically and compile it to byte code. In fact, the JSP technology is based on just that principle, in which the JSP is compiled at runtime to a servlet class, which is then run by the JVM.

In C#, too, you can generate the code and compile it at runtime. However, C# goes a step further and provides an API for actually dealing with the generated IL, a capability known as reflection emit. This would be equivalent to a Java API that manipulates byte code. The classes in the C# System.Reflection.Emit namespace can be used to programmatically generate IL instructions.

To better understand what we mean by this, let's look at a simple example. Listing ...

Get .NET for Java Developers: Migrating to C# 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.