Please note, this is a STATIC archive of website technosmarter.com from 20 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
 

C# this keyword


In C# programming, the "this" is a keyword which is used to refer to the current instant of class. In C# language, this keyword represents the "this" pointer of class. In C#, the "this" keyword is used to refer to the current class instant variable. The c# this keyword is used to call a constructor from a constructor in the same class.

Let's create an example of this keyword in C# programming.

 

C# this keyword example -


using System.IO;
using System;

class Employee {
   public int emp_id, emp_age;
   
   public String emp_name; 
   public double emp_salary; 
   
   public Employee(int emp_id, string emp_name, int emp_age,double emp_salary) {
      this.emp_id = emp_id;
      this.emp_name = emp_name;
      this.emp_salary = emp_salary;
      this.emp_age = emp_age;
   }

   public void displayEmpData() {
      
      Console.WriteLine("Employee ID= "+emp_id + " ," +"Employee Name=" +emp_name+" ,"+"Employee Age=" +emp_age+ ", "+"Employee Salary="+emp_salary);
   }
}

class EmployeeDetails {
   public static void Main(string[] args) {
      Employee emp1 = new Employee(104, "Raman",26,  30000 );
     Employee emp2 = new Employee(105, "Mohan", 27, 25000 );
    

      emp1.displayEmpData();
      emp2.displayEmpData();
     
   }
}

Output -

Employee ID= 104 ,Employee Name=Raman ,Employee Age=26, Employee Salary=30000
Employee ID= 105 ,Employee Name=Mohan ,Employee Age=27, Employee Salary=25000


In the above example of C# this keyword, you can see the work of this pointer. In the above example, we used C# this pointer to separate the method arguments with class fields.

 

In this way, you can use the C# this pointer to separate method argument and class fields.

Let's create another example to pass keyword as a method parameter in C# program.

C# this keyword example: keyword as a method parameter- 


// this pointer in C# code .
// We can pass keword as method parameter :this  
using System; 
class Student 
{ 
   string name; 
   string address; 
      
    // Constructor  
    Student() 
    { 
       name="Ram"; 
       address="India";
    } 
      
    // Method that receives 'this'  
    // keyword as parameter 
    void show(Student std) 
    { 
        Console.WriteLine("Student Name="+name+", "+"Student Address="+address); 
    } 
  
    // Method that returns current 
    // class instance 
    void getData() 
    { 
        show(this); 
    } 
  
    // Main Method 
    public static void Main(String[] args) 
    { 
       Student std = new Student(); 
        std.getData(); 
    } 
}

Output -

Student Name=Ram, Student Address=India 


In the above example, we created a student class in C#. In the class we listed student data and displayed via this keyword as the parameter.


Please Share

Recommended Posts:-