Chapter 35. System.Reflection

System.Reflection is the API that exposes the full-fidelity metadata of the .NET environment to the C# programmer. In short, it permits complete access to compile-time data at runtime. Everything is available, including fields, methods, constructors, properties, delegate types, and events. The reflection API (as exposed by the System.Reflection namespace) offers some truly unique capabilities unavailable in other compile-time bound languages such as C++. The closest the average COM programmer has come to using reflection is the IDispatch interface and/or type libraries. Reflection, fortunately, is at once both easier to use and far more powerful.

Reflection offers up a number of possible approaches to use. “Introspection” is the act of using the reflection APIs to discover information about a component assembly (and its constituent types) at runtime without any prior (compile-time) knowledge of it. This approach was first popularized by tools such as Visual Basic and numerous Java IDEs that offered GUI-based construction of visual interfaces. The third-party component was dropped into some well-known location, and the IDE “discovered” it and offered it on a toolbar the next time the IDE was started.

Along similar lines, reflection is often used as part of development tools; for example, the .NET utility xsd.exe uses metadata to generate XML Schema documents that correspond to .NET declared types. A C# programmer could use reflection to generate SQL ...

Get C# in a Nutshell 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.