Chapter 17. Reflection and Metadata
As we saw in Chapter 16, a C# program compiles into an assembly that includes metadata, compiled code, and resources. Inspecting the metadata and compiled code at runtime is called reflection.
The compiled code in an assembly contains almost all of the content of the original source code. Some information is lost, such as local variable names, comments, and preprocessor statements. However, reflection can access pretty much everything else, even making it possible to write a decompiler.
Many of the services available in .NET and exposed via C# (such as
dynamic binding, serialization, data binding, and Remoting) depend on the
presence of metadata. Your own programs can also take advantage of this
metadata, and even extend it with new information using custom attributes.
The System.Reflection
namespace houses
the reflection API. It is also possible at runtime to dynamically create
new metadata and executable instructions in IL (Intermediate Language) via
the classes in the System.Reflection.Emit
namespace.
The examples in this chapter assume that you import the System
and System.Reflection
, as well as System.Reflection.Emit
namespaces.
Reflecting and Activating Types
In this section, we examine how to obtain a Type
, inspect its metadata, and use it to
dynamically instantiate an object.
Obtaining a Type
An instance of System.Type
represents the metadata for a type. Since Type
is widely used, it lives in the
System
namespace rather than the
System.Reflection ...
Get C# 3.0 in a Nutshell, 3rd Edition 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.