You Reflection is a technique that allows us to access assembly’s metadata during run-time. To be able to use reflection you need to add System.Reflection to your using statements. Metadata are information stored in assembly ‘s that describe assembly’s types and members. Information that metadata provides can be broken down in 3 main areas:
- Information about assembly itself:
- Identity of a assembly, such as name, version, culture, public key
- Accessible types and their security information
- Other assemblies that inspected assembly depends on
- Information about types
- Type name, access modifiers, base class and implemented Interfaces
- Types members and all of their information
Why do we use reflection?
You would usually use it for a few reasons:
- You need to access assembly but have no access to it during design time.
- Access to assembly is needed but you have no access to it during compile time.
- Your team has provided you a dll file instead of entire solution.
- You want to inspect it or fine tune 3rd party assembly.
- Some variable needs to be changed during run-time.
- Some type or member is inaccessible to you during design time.
Pros and cons of using reflection
Usage of reflection can be beneficial if we do not have access to some assembly during compile time, because we can access assembly’s private fields, methods… We can for instance instantiate class of a type that we previously had no access to.
Heavily using reflection can influence our applications speed or can be a cause of problem in case of misuse. Changing value of a field can also ruin your day because although you can access fields you still cannot see how that field is implemented or in what way other parts of an assembly use that field.
To learn more continue to next page where we will look at Type class.