Reflection
For the attributes in the metadata to be useful, you need a way to access them, ideally during runtime. The classes in the Reflection
namespace, along with the System.Type
class, provide support for examining and interacting with the metadata.
Reflection is generally used for any of four tasks:
- Viewing metadata
This might be used by tools and utilities that wish to display metadata.
- Performing type discovery
This allows you to examine the types in an assembly and interact with or instantiate those types. This can be useful in creating custom scripts. For example, you might want to allow your users to interact with your program using a script language, such as JavaScript, or a scripting language you create yourself.
- Late binding to methods and properties
This allows the programmer to invoke properties and methods on objects dynamically instantiated, based on type discovery. This is also known as dynamic invocation.
- Creating types at runtime (reflection emit)
The ultimate use of reflection is to create new types at runtime and then to use those types to perform tasks. You might do this when a custom class, created at runtime, will run significantly faster than more generic code created at compile time.
Viewing Metadata
In this section, you will use the C# reflection support to read the metadata in the MyMath
class.
Start by obtaining an object of the type MemberInfo
. This object, in the System.Reflection
namespace, is provided to discover the attributes of a member and to provide access ...
Get Programming C# 3.0, 5th 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.