Reflection In C#

Introduction

In this article, I’ll discuss about C# Reflection with an example. Here we’ll learn the way of getting type information using different ways and use of properties and methods of C# Reflection type class. Advanced Reflection topics like dynamically loading an assembly and late binding will also be discussed in this article. To complete the tutorial we have implemented here C# dictionary.

What is Reflection in C#?

Reflection provides objects (of type Type) that describe assemblies, modules and types. We can 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. If we use attributes in our code, reflection enables us to access them.

Here's a simple example of reflection using the static method GetType - inherited by all types from the Object base class - to obtain the type of a variable:

  1. // Using GetType to obtain type information:   
  2. int i = 42;  
  3. System.Type type = i.GetType();  
  4. System.Console.WriteLine(type);  
The output is: 

    System.Int32

The following example uses reflection to obtain the full name of the loaded assembly.

  1. // Using Reflection to get information from an Assembly:  
  2. System.Reflection.Assembly info = typeof(System.Int32).Assembly;  
  3. System.Console.WriteLine(info);  
The output is: 

    mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Real time implementation

Firstly, we will create a C# console application and add two classes named Student.cs and StudentFunction.cs. The Student.cs class contains some properties of Student and the StudentFunction.cs class contains methods returning different properties value.

Student.cs class

  1. public class Student  
  2. {  
  3.    public string Name { getset; }  
  4.    public string University { getset; }  
  5.    public int Roll { getset; }  
  6. }  
StudentFunction.cs class
  1. class StudentFunction  
  2.     {  
  3.         private Student student;  
  4.         public StudentFunction()  
  5.         {  
  6.             student = new Student  
  7.             {  
  8.                 Name = "Gopal C. Bala",   
  9.                 University = "Jahangirnagar University",   
  10.                 Roll = 1424  
  11.             };  
  12.         }  
  13.   
  14.         public string GetName()  
  15.         {  
  16.             return student.Name;  
  17.         }  
  18.   
  19.         public string GetUniversity()  
  20.         {  
  21.             return student.University;  
  22.         }  
  23.   
  24.         public int GetRoll()  
  25.         {  
  26.             return student.Roll;  
  27.         }  
  28.     }  
Our goal is to dynamically create an instance of StudentFunction and get values from GetName(), GetUniversity() and GetRoll() method at the compile time.

In Program.cs class we need to create a Dictionary which contains the method name as string. The name of the method here as string will be compared with the given string with dynamic tag formatted as [tag name]. If both matches, then we need to get the method type.

The Dictionary will be like the following:
  1. private static Dictionary<stringstring> GetMethodsDictionary()  
  2. {  
  3.    var dictionary = new Dictionary<stringstring>  
  4.    {  
  5.       {"GetName""GetName"},   
  6.       {"GetUniversity""GetUniversity"},  
  7.       {"GetRoll","GetRoll"}  
  8.    };  
  9.    return dictionary;  
  10. }  
In Main function under Program.cs class we have to call GetMethodsDictionary().
  1. _methodDictionary = new Dictionary<stringstring>();  
  2. _methodDictionary = GetMethodsDictionary();  
Now we’ll write the code for creating the instance of StudentFunction at compile time.
  1. var type = typeof(StudentFunction);  
  2. var studentFunctionInstance = Activator.CreateInstance(type, new object[] { });  
The string will be like the following that contains the dynamic tag based on which we have to retrieve value of student properties.
  1. var testString = "Hello [GetName], your university name is [GetUniversity] and roll is [GetRoll]";  
Here [GetName], [GetUniversity] and [GetRoll] are actually method names which will be compared with the methods declared in StudentFunction class.

Now we will check the mentioned tag ([GetName] and others..) from the defined string using Regular Expression and invoke the value receiving from the methods of StudentFunction.
  1. var match = Regex.Matches(testString, @"\[([A-Za-z0-9\-]+)]", RegexOptions.IgnoreCase);  
  2. foreach (var v in match)  
  3. {  
  4.    var originalString = v.ToString();  
  5.    var x = v.ToString();  
  6.    x = x.Replace("[""");  
  7.    x = x.Replace("]""");  
  8.    x = _methodDictionary[x];  
  9.   
  10.    var toInvoke = type.GetMethod(x);  
  11.    var result = toInvoke.Invoke(studentFunctionInstance, null);  
  12.    testString = testString.Replace(originalString, result.ToString());  
  13. }  
So the entire Program.cs class will be like the following:
  1. class Program  
  2. {  
  3.     private static Dictionary<stringstring> _methodDictionary;  
  4.     static void Main(string[] args)  
  5.     {  
  6.         _methodDictionary = new Dictionary<stringstring>();  
  7.         _methodDictionary = GetMethodsDictionary();  
  8.   
  9.         var type = typeof(StudentFunction);  
  10.         var studentFunctionInstance = Activator.CreateInstance(type);  
  11.   
  12.         var testString = "Hello [GetName], your university name is [GetUniversity] and roll is [GetRoll]";  
  13.         var match = Regex.Matches(testString, @"\[([A-Za-z0-9\-]+)]", RegexOptions.IgnoreCase);  
  14.         foreach (var v in match)  
  15.         {  
  16.             var originalString = v.ToString();  
  17.             var x = v.ToString();  
  18.             x = x.Replace("[""");  
  19.             x = x.Replace("]""");  
  20.             x = _methodDictionary[x];  
  21.   
  22.             var toInvoke = type.GetMethod(x);  
  23.             var result = toInvoke.Invoke(studentFunctionInstance, null);  
  24.             testString = testString.Replace(originalString, result.ToString());  
  25.         }  
  26.   
  27.         Console.WriteLine(testString);  
  28.     }  
  29.   
  30.     private static Dictionary<stringstring> GetMethodsDictionary()  
  31.     {  
  32.         var dictionary = new Dictionary<stringstring>  
  33.         {  
  34.             {"GetName""GetName"},   
  35.             {"GetUniversity""GetUniversity"},  
  36.             {"GetRoll","GetRoll"}  
  37.         };  
  38.         return dictionary;  
  39.     }  
  40. }  
Output Window

Output Window