C# Reflection With Examples

Defining Reflection In C#

Introduction: In C#, Reflection is a process of inspecting or modifying metadata of an assembly at the runtime.

Reflection allows us to create an instance of a type without using the ‘new‘ operator and to invoke its methods, fields, and properties dynamically.
To work with reflection in .Net, we must include the System.Reflection namespace in our program.

Metadata contains information about the methods, properties, variables, etc. declared inside of an assembly.

When to use Reflection?

Reflection can be useful in the following scenarios:

    • To achieve the late binding and to access methods, fields, and properties of type inside an assembly.
    • For instantiating types in an assembly at the runtime by using ‘Activator.CreateInstance‘ method.
    • Reflection can be used to access attributes from the code.
    • To create a shared assembly.
    • To solve the DLL hell problem by creating a shared assembly.
    • Reflection ease the process of deployment, we can do versioning of an assembly using reflection (Example: [assembly: AssemblyVersion(“1.0.0.0”)]).
    • Reflection can be also used to access private data members of a class.

Dynamic Assembly Loading Using Reflection

Let’s write a C# program to create a private assembly and load that assembly at the runtime by using reflection.

Write the following program in notepad or Visual Studio editor and save the file as ‘User.cs’ in the local folder( Example D:\User\User.cs).

using System;
namespace Reflection
{
    // Class
    public class User
    {
        // field
        public int userId = 52894;

        //Method
        public string GetName()
        {
            return "Mr. Shekh Ali";
        }

        //Method
        public string Print(string message)
        {
            return message;
        }
    }
}

Open Visual Studio command prompt and execute the following command.
csc /t:library User.cs

Command to generate assembly-reflection
Command to generate a private assembly.

A new assembly ‘User.dll’ is created in the ‘D:/User/’ drive.

Private Assembly: Reflection
A private assembly is created after executing the above command.

Now create a new console application, and write the following program to load the assembly at the runtime using the reflection.

Example 1:

using System;
using System.Reflection;
namespace Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
         // Dynamically load assembly from file User.dll
          Assembly assembly = Assembly.LoadFile(@"D:\User\User.dll");

         // Get type of class 'User' from the loaded assembly  
          Type type = assembly.GetType("Reflection.User");

         // Create instance of 'User' class
          object instance = Activator.CreateInstance(type);

         // Call method: public string GetName()
          MethodInfo method = type.GetMethod("GetName");

        // Invoke method: 
           string name = Convert.ToString(method.Invoke(instance, null));
         //Call public field
          FieldInfo field = type.GetField("userId");
          int userId = (int)field.GetValue(instance);

          Console.WriteLine(userId);
          Console.WriteLine(name);         
          Console.ReadLine();

        }
    }
}


Output: Reflection
The output of the above program.

In the above program, we are calling field and method data from the assembly at the runtime.

System.Reflection Namespace

The following are the some commonly used classes in the reflection namespace:

Assembly: This class allows us to load, investigate and manipulate an assembly dynamically.

MethodInfo: This class is used to hold the information such as the name, return type, parameters, access modifiers, etc. of a specified method.Use the ‘GetMethods’ or ‘GetMethod’ method of a Type to invoke a specific method.

PropertyInfo: This class is used to hold the information such as the name and data type of a property and to get or set the property values.

FieldInfo: This class provides access to field metadata. It is used to discover information such as the name, access modifiers (such as public or private) and implementation details (such as static) of a field, and to get or set field values.

EventInfo: This class holds information such as the name, event-handler data type, custom attributes, etc. for a given event. Use this class to inspect events and to bind to event handlers.

ConstructorInfo: This class is used to discover information such as the name, parameters, access modifiers and implementation details of a constructor.

CustomAttributeData: This class is used to get information on custom attributes or to examine attributes without having to create instances of them.

Access private method in C# using reflection

In C#, Technically calling a private method of one class into another class is not possible.
However, by using reflection it is possible to call a private method from one class to another. Following is the C# program where we have created a User class with a private method.
Here, we will try to invoke the private method of User class into the Main() method of the Program class.

Example 2:

using System;
using System.Reflection;
namespace Reflection
{
    class User
    {
        // private method
        private string PrivateMethod()
        {
            return "Private method executed !!";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

          // Create object of User class
           User instance = new User();

         // Get type of User class 
          Type type = typeof(User);

         // Call private method with required binding constraints. 
          MethodInfo method = type.GetMethod("PrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);

        // Invoke method at the runtime 
           string name = Convert.ToString(method.Invoke(instance, null));
        
          Console.WriteLine(name);         
          Console.ReadLine();

        }
        //Output: Private method executed !!
    }
}


Calling private method using Reflection
The output of the above C# program

In the above example, we are accessing the private method of a class by using reflection.
Reflection in C# is commonly used in UI applications like ASP.NET, where we are able to set the properties of controls like TextBox, Button, ComboBox, etc. itself directly.

Hope you enjoyed this post. Thanks for visiting.

Leave a Reply