Using Reflection in C#

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:

Don’t worry if the information here is not clear to you in first glance, it will becomes easier to follow as we progress. But first, lets learn a little bit more about above shown building blocks:

Assembly

  • They are building blocks of .NET applications.
  • An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.
  • They are typically in form of .dll or .exe.
  • They contains meta-data.

Module

  • It is similar to assembly.
  • A module is a portable executable file such as .dll or .exe, containing some classes and interfaces.
  • In .NET, most assemblies contain just one module.

Type

  • A collection of members. Fields, that hold data; Methods, that can be executed and so on.
  • Some examples are Class, Struct, Enum etc.

A type contains metadata describing itself:

  • Its base type.
  • Interfaces it implements.
  • Permitted operations
  • ..others

This metadata is important when working with reflection.

Member

  • Member of a type represents its data and behavior.
  • Examples are Fields, Properties, Constructors, Events, Methods and so on.

But What does this all has to do with reflection?

Reflection

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

To do this, first, we need to get the metadata of a Type and we can use that metadata to modify our application.

Typical uses of reflections are:

  • Dynamically create an Instance of a Type.
  • Binding the Type to an existing Object.
  • Get the Type from an existing Object.
  • Invoke Type’s Methods or access its Fields and Properties.

One practical example, is that, in our code, we have a string value “MailService”. We can use this string with reflection to search the assembly for such type, create an instance of it and call methods on it, all dynamically, at run-time.

Reflection is commonly used in

  • Dependency Injection Containers
  • ORMs
  • Serilization
  • Type inspector apps.
  • Dynamic C#

Beside its uses and powerful features, there are some cons/drawbacks we might be aware of when using reflection:

  • Reflection is relatively slow.
  • Error prone due to its dynamic nature.
  • It is considered complex.

Ok, this is a lot of theory for now, next, lets see a demo.

Reflection Demo – 1

To keep things very simple, lets start with a basic demo.

I have updated the code to follows:

GetType() is our entry point for reflection libraries.

GetType() method is available for all objects and here we are using it to get a type of string instance and writing it to console.

Now, lets see, if we do not have a name variable at all, how can we get this information?

we can still get to the Type via the typeof with parameter as follows:

So, thats for the first demo. Here, we saw how to get Type of an instance if instance available, or use typeof method to get to Type when its not available or when you now the type in advance.

Demo-2

Lets practice more but this time with Vehicle Model instead of built-in string type:

As you can see that GetType and typeof usage is same for user-defined-type as well and results are as expected.

Demo-3

Lets continue with another example by finding all types in an assembly:

GetExecutingAssembly as name implies refers to currently executing assembly. We can see that console output shows all the types defined in our code.

Instead of all types, we can also search for a particular type. Check the following code:

In debug view, we can see that a great wealth of information available to us. We’ll explore more of this later.

Demo 4 – Loading External Assembly

It is also common that types might be defined in external assemblies that are not loaded yet.

Let’s see a demo to get to those types.

Assembly.Load() is another commonly used method in reflection code-bases.

In the code we are also getting Modules information using GetModules() and GetModule() methods.

So, we saw few demos and get started interacting with reflection API and this seems like a good stopping point as well.

It might seems like not much, but we took our first steps towards learning this powerful API. We’ll resume our journey in the next post.

Summary

In this post, we learn about few basics of reflection API in C# and also saw some simple demos. We got ourselves familiarized with some boiler-plate reflection code and in upcoming posts we will build on this learning.

Source code is available from this git repository.

Let me know if you have some questions or comments. Till next time, Happy Coding.

1 thought on “Using Reflection in C#”

Comments are closed.