In part-1 of this series, we started our journey with reflection basics.
We learned that Reflection is the process by which a software can observe and modify its own structure and behavior.
For that to happen, we need helper objects to dynamically create instance of a type, bind the type to an existing object and getting the type from an existing object.
These helper objects are contained in System.Reflection namespace.
We also learned that Reflection is commonly used but it should be used with care as being relatively slow, error prone due to its dynamic nature and being complex in general.
If you are new to these topics, I’ll suggest to read the part-1 first as we will be building on top of previous learning.
Demo — Type Information using Reflection
Lets see the code for a vehicle entity:
We have a simple class Truck, which is extending a base class Vehicle.
All the source code is available from this git repository.
Following screenshot is showing the use of helper methods from reflection API to get details about Truck Type. Here we are listing all the methods implemented by Truck type:
(Note, it is not listing protected method UpdateSpeed(), we will come back to it when discussing BindingFlags later in post).
Reflection API is not limited to methods only, we can get constructors, events, fields, properties and all other kind of information. Following example shows the code to get the properties of a type:
GetProperties() returns and array of PropertyInfo type which contains information about…