Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Reflection?
2.1.
Uses
2.2.
Commonly Used Classes
2.3.
Example
3.
Binding
3.1.
Example
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Reflection in C#

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In this blog, we will learn about the Reflections in C#,  so let's begin with an introduction of the Reflections, and then we will learn how we use them with their examples. 

In C#, Reflection is used to get metadata on types at runtime. In another way, you can use Reflection to dynamically analyze metadata of the types in your program — you can get information on the loaded assemblies, and the types declared in them—the namespace System. Reflection enables you to obtain data about the loaded assemblies and the elements within them like classes, methods, and value types.

What is Reflection?

Objects that describe assemblies, modules, and types are provided by Reflection. You may use Reflection to dynamically generate a type instance, link a type to an existing object, or get a type from an existing object and use its methods, fields, and attributes. Reflection allows you to access characteristics in your code if you use them. 

Here's a primary reflection example that shows how to get the type of a variable using the GetType() function, which is inherited by all types from the Object base class.

using System;  
public class ReflectionExample  
{  
   public static void Main()  
    {  
        int a = 10;  
        Type type = a.GetType();  
        Console.WriteLine(type);  
    }  
}

Output:

System.Int32.

Uses

In the following scenarios, Reflection is beneficial:

  • When you need to access metadata properties in your software. 
  • In an assembly for inspecting and instantiating types.
  • For creating new types at the run time.
  • Accessing methods on types constructed at run time to conduct late binding.

Commonly Used Classes

Some of the Commonly Used Classes are as follows:

Class

Description

Assembly

explains an assembly, which is a reusable, versionable, and self-describing building element 

AssemblyName

Identifies a certain assembly by its name.

ConstructorInfo

Describes a class constructor and provides metadata access.

MethodInfo

Provides information about the class method as well as access to its metadata.

ParameterInfo

Describes a method's arguments and provides access to its information.

EventInfo

Describes the information about the event and provides access to its metadata.

PropertyInfo

Discovers a property's characteristics and offers access to property metadata.

MemberInfo

It gets information about a member's qualities and gives you access to their metadata.

Example

The namespace for Reflection is Reflection.System. The assembly module, MemberInfo, PropertyInfo, MethodInfo, ConstructorInfo, FieldInfo, EventInfo, and so on, is defined in the Reflection namespace.

using System;
using System.Reflection;

public class MyClass
{
   public virtual int AddNumb(int numb1,int numb2)
   {
     int result = numb1 + numb2;
     return result;
   }
}

class MyMainClass
{
  public static int Main()
  {
    Console.WriteLine ("Reflection.MethodInfo");
    // Create MyClass object
    MyClass myClassObj = new MyClass();
    // Get the Type information.
    Type myTypeObj = myClassObj.GetType();
    // Get Method Information.
    MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
    object[] mParam = new object[] {5, 10};
    // Get and display the Invoke method.
    Console.Write("First method - " + myTypeObj.FullName + " returns " +  
                         myMethodInfo.Invoke(myClassObj, mParam) + "\n");
    return 0;
  }
}

Output:

Reflection.MethodInfo

First method - MyClass returns 15

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Binding

When an object is assigned to an object variable of a specified type, the C# compiler uses the.NET Framework to complete the binding. There are two types of bindings that C# can perform: Early Binding and Late Binding

Early binding may be explained as the compiler knowing what sort of object it is and its members and types. When using Auto Intellisense, developers may view all available members of a class while typing in the editor.

Student stud = new Student();  
stud.displayName(); 

The term "late binding" refers to binding that occurs during the execution of a program. The compiler has no idea what sort of object it is or what methods and attributes it has. Reflections are used to create the late binding.

Example

using System;
using System.Reflection;

namespace ReflectionConcept  
{  
    public class Employee  
    {  
        public int empID { get; set; }  
        public string empName { get; set; }  
        public float Salary { get; set; }  
  
        public Employee()  
        {  
            this.empID = -1;  
            this.empName = string.Empty;  
            this.Salary = 0;  
        }  
  
        public Employee(int id, string name, float salary)  
        {  
           this.empID = id;  
            this.empName = name;  
            this.Salary = salary;  
        }  
  
        public void displayName()  
        {  
            Console.WriteLine("Name :" + this.empName);  
        }  
  
        public void displayemp(string name)  
        {  
            Console.WriteLine("Name :" + name);  
        }  
  
  
        public void printSalary()  
        {  
            Console.WriteLine("Salary :" + this.Salary);  
        }  
  
    }  
  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            Assembly executable = Assembly.GetExecutingAssembly();  
            Type Ltype =executable.GetType("ReflectionConcept.Employee");  
  
            object objEmployee = Activator.CreateInstance(Ltype);  
  
            MethodInfo method = Ltype.GetMethod("displayemp");  
  
            string[] parameter = new string[1];  
  
            parameter[0] = "Amisha";  
  
            string employeeName=   (string)method.Invoke(objEmployee, parameter);  
  
            Console.ReadLine();  
        }  
          
    }  
} 

Output:

Name :Amisha

We are done with the blog, lets’ move to FAQS.

FAQs

  1. What is Reflection in C#?
    Reflection is a runtime type discovery mechanism that examines metadata, CIL code, late binding, and self-generating code. 
  2. When to use Reflection in C#?
    We utilize Reflection if we wish to know assembly information at runtime. In the.NET Framework, data binding is done through Reflection. It's also used in the.NET Framework for testing.
  3. Why use Reflection in C#?
    For getting metadata information from the assembly, Reflection is essential.
  4. What is Late Binding?
    The term "late binding" refers to binding that occurs during the execution of a program. The compiler has no idea what sort of object it is or what methods and attributes it has. Reflections are used to create the late binding.
  5. What are the disadvantages of Late Binding?
    The drawback of Late Binding is that if you misspell a method or class name, the compiler will not detect it at compilation time, and the code will still compile correctly. In the vast majority of cases, Early Binding is preferred to Late Binding.

Also Read About - singleton design pattern in c#

Key Takeaways

In this article, we have extensively discussed C# Reflections, learned about their uses and saw how Reflection helps in Late Binding. You can visit here to learn more about C#.

We hope that this blog has helped you enhance your knowledge regarding C# Reflections and if you would like to learn more, check out our articles in the code studio library. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
C# Generics
Next article
Thread Synchronization
Live masterclass