Programming with Reflection in the .NET Framework Using Managed C++
- Traditional C++ Runtime Type Information
- The Power of Reflection
- Why You Should Understand Reflection
- The Type Class Is Just Another Type
- An Analogy
- When Not to Use Reflection
- How Reflection Works
- A Reflection Example
- Summary
This article takes a look at the weird, powerful, and even entertaining concept of reflectionhow it works and how it can be used. Although we focus on using Visual C++ with managed extensions, other .NET languages such as C# and VB.NET are equivalent in terms of the reflection capabilities described in here.
Traditional C++ Runtime Type Information
Traditional C++ has limited support for programming with type information, but the managed C++ extensions make a great deal more possible by means of reflection. Traditional C++ supports runtime type information (RTTI) that allows you to do little more than test the type of an expression. The type_info class, the typeid operator, and the dynamic_cast operator are all that is available. The type_info class encapsulates type information generated by the compiler, and the typeid operator allows the type of a class or an object to be tested at runtime. The dynamic_cast operator just allows you to cast in a type-safe manner.
Unfortunately, these capabilities are very limited and passive because much of the detailed type information is lost during compilation. For example, you cannot programmatically obtain a list of all the methods in a class or generate an entirely new class using RTTI. On the other hand, managed C++ supports the rich type information manipulation capabilities made famous by reflection in the Java language. In the .NET world, reflection is made possible by metadata that describes detailed type information that is emitted by the compiler and stored along with the code in the assembly.