In this article, I am going to discuss Reflection in C# with Examples. Reflection in C# determines or inspects the content of an assembly. You can also use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. In this article, we are basically going to discuss what is reflection in C#, how to implement reflection, and finally, we will discuss when to use reflection in C#.
Reflection is needed when you want to determine or inspect the content of an assembly. Here, content means the metadata of an assembly like what are the methods in that assembly, what are the properties in that assembly, are they public, are they private, etc.
For example, one of the biggest implementations of Reflection is Visual Studio itself. Suppose, in visual studio, we create an object of the String class, and when we press obj. then visual studio intelligence shows all the properties, methods, fields, etc. of that object as shown in the below image. And this is possible because of the Reflection in C#.
So, basically, Reflection inspects the assembly and shows the metadata of that assembly. Now, I hope you understand the definition of Reflection. Now, let us proceed and understand how to implement reflection in C#.
So, now we are going to write a simple example implementing reflection in C# language. So, first, create a console application with the name ReflectionDemo. And to this ReflectionDemo solution, let us add a class library project with the name SomeClassLibrary. Once you add the Class Library Project, your solution should look like the following.
As you can see, the Class Library Project is created with a class called Class1.cs. Now, modify the Class1.cs class file as follows. As you can see, here we have created some private and public fields, some private and public properties, and some private and public methods.
Now, build the Class Library Project. And once you build the Class Library Project an assembly (with extension .DLL) will be generated inside the Project’s bin=> Debug location as shown in the below image.
So, basically, in my machine, in the following location, the SomeClassLibrary.dll assembly is created. Copy the location.
D:\Projects\ReflectionDemo\SomeClassLibrary\bin\Debug
Now, remove the Class Library Project from the solution. To do so, right-click on the Class Library Project and then click on the Remove option as shown in the below image.
Once you click on the Remove option, one popup will come simply click Yes to remove the project. Once you remove the Class Library Project, then your solution will contain only the ReflectionDemo Console Application as shown in the below image.
Now, what we need to do is, we need to display the Properties, Methods, and Variables of the SomeClassLibrary assembly using Reflection. Implementing reflection is a three steps process. The steps are as follows.
So, basically, first, we need to import the Reflection namespace and then we need to get the type of the object and once we get the type of the object, then we can go and browse the metadata i.e. browse the methods, properties, variables, etc. So, let us implement these three steps one by one.
using System.Reflection;
First, we need to get the Reference of the assembly. To get the reference of the assembly we need to use the Assembly.Loadfile method and we need to provide the Path of the assembly (you need to provide the DLL Path where exactly the DLL exists in your machine) as follows.
var MyAssembly = Assembly.LoadFile(@”D:\Projects\ReflectionDemo\SomeClassLibrary\bin\Debug\SomeClassLibrary.dll”);
Once you get the reference of the assembly, the next step is to get the class reference. What it means once you get the assembly reference, from that assembly reference you need to get the class reference. That reference might contain multiple classes. For this, we need to call the GetType method on the assembly reference, and to this get type method, we need to provide the fully qualified name of the class i.e. Namespace.ClassName is as follows. We need to fetch the details of the class Class1.
var MyType = MyAssembly.GetType(“SomeClassLibrary.Class1”);
Once you get the class reference i.e. the type, then you need to create an instance of that class or type. To create an instance of a class dynamically in C#, we need to use Activator.CreateInstance method and to this method, we need to pass the type object as follows.
dynamic MyObject = Activator.CreateInstance(MyType);
Once the above step is executed, the object is created. Once the object is created, next we need to get the type of the class. To get the type of the class, we can use the GetType method as follows.
Type parameterType = MyObject.GetType();
Using this parameterType object we can access the metadata i.e. we can access the methods, properties, fields, etc. of a class.
In this step, we need to browse the metadata of the assembly. To get all the public members of the type, we need to use GetMembers() method, to get all the public methods, we need to use GetMethods() method, to get all the public variables or fields, we need to use GetFields() method, and to get all the public properties of the assembly we need to use GetProperties() method as shown in the below image.
Some of the useful methods are as follows:
The following is the complete example code. The following example code is self-explained, so please go through the comment liens for a better understanding.
Here, you can see in all methods, it also fetches the object class methods. This is because the object is the superclass of all classes in the .NET Framework. Here, get_P1 and set_P1 are the setter and getter methods of the public property P1. So, this is how you can go and extract metadata of an assembly using Reflection in C#.
So, basically what we want to do is, once we get the Type then we want to show the class name, fully qualified class name, and namespace name. For this, we need to call the Name, FullName, and Namespace properties as shown in the below example.
So, this is how you can extract the type information of an assembly using Reflection in C#. Now, let us see some other benefits of using Reflection in C#.
One of the good features of reflection is it will inspect the metadata of an assembly and we already discussed this. Another good feature of using Reflection is that we can invoke the members of an assembly in C# using Reflection. So, if you remember we have defined one public method i.e. Method1 in our class library assembly and we want to invoke that method using reflection. To invoke the method of assembly using reflection, we need to use the InvokeMember method as shown in the below image.
The following is the signature of the InvokeMember method.
InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args): This method invokes the specified member, using the specified binding constraints and matching the specified argument list. It returns an object representing the return value of the invoked member. This method takes the following parameters:
Note: This method of invocation is completely done at runtime. If the method exists at runtime, it will invoke the method else it will throw an exception. That means Reflection in C# does the complete dynamic invocation of the method during runtime.
The complete example code is given below.
Note: Reflection is used to find all types in an assembly and/or dynamically invoke methods in an assembly. This includes information about the type, properties, methods, and events of an object. With Reflection, we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.
So, basically using reflection we can inspect the metadata of an assembly as well as we can invoke methods are runtime. There is a keyword called dynamic which was introduced in C# 4.0 and does the same thing as reflection. There are many confusions between dynamic and reflection in C#. So, in the next article, I am going to discuss what is dynamic and what are the differences between dynamic and reflection in C#.
In the next article, I am going to discuss Dynamic Type in C# with Examples. Here, in this article, I try to explain Reflection in C# with Examples. I hope you enjoy this Reflection in C# with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.