Reflection In C# With Examples

Reflection in C# provides objects that encapsulate assemblies, modules, and types. It allows you to dynamically instantiate types, binds types to existing objects, or get the types of existing objects.
Reflection allows you to access the methods, fields, and properties of the type at runtime.

Reflection In C#
Reflection In C#

Defining Reflection In C#

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.

The classes in the System.Reflection and System.Type namespaces allow you to get information about the loaded assembly and the types (such as classes, interfaces) defined in it.

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:

    • Reflection in C# can be used to implement late binding and dynamically access methods, fields, and properties type in an assembly.
    • We use reflection to find assembly information at run time. Reflection is used in the.NET Framework to perform data binding.
    • It can be used for instantiating types in an assembly at the runtime by using the ‘Activator.CreateInstance‘ method.
    • If you want information about attributes on a type or method, you can use reflection.
    • Reflection can be used to create a shared assembly.
    • Reflection can be used to solve the DLL hell problem by creating shared assemblies.
    • 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 In C#

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 using reflection in C#
Command to generate a private assembly.

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

Create Private Assembly Using Reflection in c#
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: Load the assembly at the runtime using the reflection in C#.

Viewing Metadata

In the following example, the MethodInfo and FieldInfo objects of the System.Reflection class must be initialized to discover the attributes of the method and field associated with the class.

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();

        }
    }
}


image Output of Reflection program
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 some of the most commonly used reflection namespace classes:

    • Assembly: This class allows us to load, investigate and manipulate an assembly dynamically.
    • Module: Module class in reflection is used to discover information, such as the assembly containing the module and the classes in the module. You can also retrieve a list of all global methods and non-global methods specified on the module.
    • MethodInfo: This class is used to hold data about a method, such as its name, return type, parameters, access modifiers, and so on. To invoke a specific method, use the Type’s GetMethods() or GetMethod() method.
    • PropertyInfo: This class in reflection is used to contain information such as the name and data type of the property, and to get or set the value of the property.
    • FieldInfo: This class allows you to access field info. It is used to retrieve or update field values as well as discover information such as field names, access modifiers (such as public or private), and implementation details.
    • 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.Use the GetConstructors() or GetConstructor() method of Type to call a specific 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 using reflection in C#

In C#, calling private methods from one class to another is technically impossible.
However, using reflection can call private methods from one class to another. Below is a C# program where we created a user class with private methods.
Here, we will try to call the private method of the User class to the Main () method of the Program class.

Example 2: Invoke the private method using reflection

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 in c#
The output of the above C# program

In the example above, we used reflection to access the private methods of the class. Reflection in C # is often used in user interface applications such as ASP.NET. We can directly set the properties of TextBox, Button, ComboBox, and other controls.

To read more about reflection, please visit this MSDN link.

Conclusion:

I hope you found this post useful in learning about reflection in C#. Your comments, suggestions, and constructive criticism are much appreciated.

Recommended Articles

    1. 10 Difference between interface and abstract class In C#
    2. Exception Handling in C#| Use of try, catch and finally block
    3. C# Enum | How To Play With Enum in C#?
    4. C# extension methods with examples
    5. Properties In C# with examples
    6. Generic Delegates in C# With Examples
    7. Constructors in C# with Examples
    8. C# Dictionary with Examples
    9. IEnumerable Interface in C# with examples
    10. Access Modifiers in C#

Leave a Reply