C# this Keyword

In C#, this is a keyword that refers to the current instance of a class. It is also used to pass the object to another method as a parameter and also used to call a constructor of another class from the same class in a program.

It is used to access members from the constructors, instance methods, and instance accessors.

Let us see an example of this keyword in C# programming.


Example: C# program for this keyword

using System;

namespace program
{
  public class Student
  {
    public int roll;
    public String name;
    public int age;
    public String subject;

    //constructor
    public Student(int r, String n, int a, String sub)
    {
      this.roll = r;
      this.name = n;
      this.age = a;
      this.subject = sub;
    }

    public void display()
    {
      Console.WriteLine(roll + " " + name + " " + age + " " + subject);
    }
  }

  class StudenInfo
  {
    public static void Main(string[] args)
    {
      Student std1 = new Student(1101, "Shaun", 19, "Maths");
      Student std2 = new Student(1102, "Garen", 17, "Computer");
      Student std3 = new Student(1103, "Parker", 18, "Biology");

      std1.display();
      std2.display();
      std3.display();

    }
  }
}

Output:

1101 Shaun 19 Maths
1102 Garen 17 Computer
1103 Parker 18 Biology