Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

Chapter 36. System.Reflection.Emit

There are several ways to use reflection in .NET. Reflection can be used for runtime-type inspection and late-bound object creation using the types in the System.Reflection namespace. Reflection can also be used for dynamic code creation, which is supported by the types in this namespace, System.Reflection.Emit. Dynamic code creation means a programmer can programmatically create code constructs such as methods and events from within code, using the appropriate corresponding type (for example, MethodBuilder and EventBuilder). These code elements are all ingredients that can be added to a dynamic assembly, represented by an AssemblyBuilder object. Dynamic assemblies can be saved to disk as PE (Portable Executable) files, typically in DLL form. Or, alternatively, emit it directly to memory for immediate use, at the expense of persistence (memory-only types disappear when the containing AppDomain terminates).

The ILGenerator class allows you to emit the MSIL (Microsoft Intermediate Language) for your code, using the corresponding GetILGenerator() method from a builder class. This process (sometimes known as “baking”) allows you to convert the information in the builder object into a legitimate .NET type. You can then instantiate this newly created type on the spot.

The primary use of the System.Reflection.Emit namespace is to create compilers and script hosts, although many other uses are possible, including programs that dynamically create code ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata