C Sharp this keyword

C# this

To refer to the current instance of the class, “this” keyword is used in C#.

Uses of this keyword in C#:

  • To refer to the current class instance variable to easily distinguish the instance variables or the field names and names of the parameters in case they are the same.
  • To pass the current object as a parameter to another method.
  • For declaring indexers.

Example:

using System;  
   public class Employee  
    {  
        public int emp_id;   
        public String emp_name;  
        public void insert(int x, String y)  
        {  
            emp_id = x;  
            emp_name = y;  
        }  
        public void display()  
        {  
            Console.WriteLine(emp_id + " " + emp_name);  
        }  
   }  
   class Details{  
       public static void Main(string[] args)  
        {  
            Employee e1 = new Employee();  
            Employee e2 = new Employee(); 
            Employee e3 = new Employee(); 
            Employee e4 = new Employee(); 
            Employee e5 = new Employee(); 
            e1.insert(10, "Vishal Gupta");  
            e2.insert(11, "Thomas Edison");  
            e3.insert(12, "Tom Smith");  
            e4.insert(13, "Sunita Wills");  
            e5.insert(14, "David Cruise");  
            e1.display();  
            e2.display(); 
            e3.display(); 
            e4.display(); 
            e5.display(); 
 
        }  
    }

Output:

Explanation:

In the above example, we are using C# ‘this’ keyword to refer to the fields of the current class.

Please follow and like us:
Content Protection by DMCA.com