‘this’ keyword in C#


The “this” keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name.

Another usage of “this” keyword is to call another constructor from a constructor in the same class.

Here, for an example, we are showing a record of Students i.e: id, Name, Age, and Subject. To refer to the fields of the current class, we have used the “this” keyword in C# −

public Student(int id, String name, int age, String subject) {
   this.id = id;
   this.name = name;
   this.subject = subject;
   this.age = age;
} 

Example

Let us see the complete example to learn how to work with the “this” keyword in C# −

 Live Demo

using System.IO;
using System;

class Student {
   public int id, age;  
   public String name, subject;

   public Student(int id, String name, int age, String subject) {
      this.id = id;
      this.name = name;
      this.subject = subject;
      this.age = age;
   }

   public void showInfo() {
      Console.WriteLine(id + " " + name+" "+age+ " "+subject);
   }
}

class StudentDetails {
   public static void Main(string[] args) {
      Student std1 = new Student(001, "Jack", 23, "Maths");
      Student std2 = new Student(002, "Harry", 27, "Science");
      Student std3 = new Student(003, "Steve", 23, "Programming");
      Student std4 = new Student(004, "David", 27, "English");

      std1.showInfo();
      std2.showInfo();
      std3.showInfo();
      std4.showInfo();
   }
} 

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 19-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements