Chapter 13. Reflection
The CLR knows a great deal about the types our programs define and use. It requires all assemblies to provide detailed metadata, describing each member of every type, including private implementation details. It relies on this information to perform critical functions, such as JIT compilation and garbage collection. However, it does not keep this knowledge to itself. The reflection API grants access to this detailed type information, so your code can discover everything that the runtime can see. Moreover, you can use reflection to make things happen. For example, a reflection object representing a method not only describes the method’s name and signature, but it also lets you invoke the method. And in some versions of .NET, you can go further still and generate code at runtime.
Reflection is particularly useful in extensible frameworks, because they can use it to adapt their behavior at runtime based on the structure of your code. For example, Visual Studio’s Properties panel uses reflection to discover what public properties a component offers, so if you write a component that can appear on a design surface, such as a user interface element, you do not need to do anything special to make its properties available for editing—Visual Studio will find them automatically.
Note
Many reflection-based frameworks that can automatically discover what they need to know also allow components to enrich that information explicitly. For example, although you don’t need to ...
Get Programming C# 5.0 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.