Many developers see reflection as something new and mysterious. In the first of this two-part article we explain reflection in the .NET Framework and demonstrate where and how you can use this new tool in your applications.
by Lars Powers, MCSD
Mike Snell, MCSD
Dec 19, 2002
Page 1 of 5
eflection in .NET is an exciting new tool for most developers. This article shows you how to use reflection to discover objects at runtime that you did not know existed at design time, create an instance of those objects, and execute methods of those objects.
What Is Reflection?
Reflection is a means of discovering information about objects at runtime. This information can be used to execute methods and retrieve property values of these objects in a dynamic manner. Code written for the .NET Framework automatically reflects, or describes, itself. It does so via compiler-generated metadata. You can therefore use reflection in your applications to query managed code about its types (including class names, methods, and parameters) and then interact with this informationthis includes executing the discovered code. You can also use reflection to generate code at runtime, compile it, and run it.
What's the Point of Reflection?
The most obvious example of reflection is a type or object browser. Think of the Visual Studio .NET object browser. This utility can display classes exposed by an assembly, methods on those classes, parameters for those methods, etc. (see Figure 1for an example). In the past, some of this information was available to us via COM type libraries. With .NET this application data is available from the assembly itself. All .NET assemblies are self-describingthat is, they contain metadata about their types. You can query this metadata to learn about a given object. (See Sidebar: Metadata)