C# this Keyword

In c#, this keyword is used to refer to the current instance of a class, and by using this keyword, we can pass a current instance of the class as a parameter to the other methods.

 

In case if the class contains parameters and variables with the same name, then this keyword is useful to distinguish between the parameters and variables.

 

We can also use this keyword to declare indexers and to specify the instance variable in the parameter list of an extension method.

 

In c#, we should not use this keyword to refer to static fields or methods. In the same way, it cannot be used in static classes.

C# this Keyword Syntax

Following is the syntax of using this keyword in c# programming language.

 

this.instance_variable

If you observe the above syntax, this is a keyword, and instance_variable is an instance variable name.

C# this keyword Example

Following is the example of using this keyword in c# programming language to refer to the class variables and parameters of the same name and use this keyword to send an instance of the class to another class's method.

 

using System;

namespace Tutlane
{
    class User
    {
       public string name, location;
       public long marks = 470;
       public User(string name, string location)
       {
          // Use this to distinguish between parameters and variables
          this.name = name;
          this.location = location;
       }
       public void GetUserDetails()
       {
          Console.WriteLine("Name: {0}", name);
          Console.WriteLine("Location: {0}", location);
          // Passing a class instance to the method using this
          Console.WriteLine("Marks: {0}", Exams.GetPercentage(this));
       }
    }
    class Exams
    {
       public static double GetPercentage(User u)
       {
           double i = ((double)470 / 600) * 100;
           return (i);
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          User u = new User("Suresh Dasari", "Hyderabad");
          u.GetUserDetails();
          Console.WriteLine("\nPress Enter Key to Exit..");
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used this keyword to distinguish between class variables and parameters of the same name and used this keyword to send an instance of a class (User) to the method of another class.

 

When we run the above c# program, we will get the result as shown below.

 

C# this keyword Example Result

 

This is how we can use this keyword in c# programming language to refer to the instance of a class based on our requirements.