Using Reflection in C#

Jawadhasan
6 min readNov 13, 2022
Photo by Elsa Gonzalez on Unsplash

Introduction

Reflection is a process or mechanism by which a software can observe and alter its own structure and behavior at run-time.

It is a powerful capability offered by different programming languages / frameworks and it helps us building extendable systems, plugins and dynamic behaviors which are not easy to implement in a typical strongly-typed language.

Yes, Reflection is very powerful and same time also considered a complex topic. There is also some boiler-plate code from reflection API which you will see and use quite often and should be familiar with, in order to get started with reflection. In this post, we’ll start with that part and get some hands-on experience as well.

I plan to write multiple posts on this topic and gradually build up our learning in an incremental manner by transitioning from easier to more advance and particle topics and corresponding examples. I think this step by step approach will help us in simplifying our learning journey.

Next, Lets see how the initial code is setup and start exploring reflection.

You can download the code from this git repository.

Initial Code Setup

Following diagram shows a very basic domain model. Vehicle class is acting as a base-class and then we have few derived classes extending the Vehicle.

Vehicles Model

Demo Code

Following is the code, which is using the vehicles model and a very typical manner.

So far code is not doing anything related to reflection.

Ok, we’ll take a pause from the application code and switch our attention towards some basics related to reflection.

.NET Application Structure

Lets start with a very basic diagram showing structure of a typical .NET application:

--

--

Jawadhasan

Software Solutions Team Lead | Cloud Architect | Solutions Architect