C# This Keyword

In C#, the "this" keyword denotes the present instance of the class. It is primarily used to access instance elements like fields, methods, and properties. This becomes crucial in scenarios where there is a naming clash with variables. Additionally, "this" is employed to trace the specific instance that is invoked to execute additional operations or computations linked to that instance.

Syntax of this keyword

It has the following syntax.

Example

this.memberName = parameterName;

In this syntax,

  • this: It represents a keyword that defines the current instance of the class.
  • memberName: It represents the name of the class's variables.
  • parameterName: It represents the local variable or parameter that is passed into the methods or a constructor.
  • Basic Example of C# this keyword

Let's consider a demonstrative instance of this keyword that pertains to the attributes of the present class in C# programming.

Example

Example

using System;

class Student

{

    private string na_me;

    private int age;

    // using Constructor 

    public Student(string na_me, int age)

    {

        this.na_me = na_me; 

        this.age = age;

    }

    public void ShowDetails()

    {

        Console.WriteLine("The name is " + this.na_me);

        Console.WriteLine("The age is " + this.age);

    }

}

class Program

{

    static void Main()

    {

        Student student1 = new Student("John", 20);

        student1.ShowDetails();

    }

}

Output:

Output

The name is John

The age is 20

Explanation:

In this instance, we define a class called Student with two attributes: name and age. Subsequently, a constructor is established to take in two arguments. Following this, the ShowDetails function is implemented to exhibit the name and age of the student. Within the main function, an instance named student1 is instantiated and assigned specific values. Then, the ShowDetails function is invoked to exhibit the student's particulars.

Initialize Class Fields and Constructors using the this keyword

Let's consider an example to demonstrate this keyword that is utilized to set up class fields and the constructor.

Example

Example

using System;

class Staff

{

    private int staff_Id;      // variable

    private string staff_Name;       

    private float staff_Salary;

    public Staff(int id, string name, float salary)

    {

        this.staff_Id = id;

        this.staff_Name = name;

        this.staff_Salary = salary;

    }

    public void ShowInfo()

    {

        Console.WriteLine($"{staff_Id}  {staff_Name}  {staff_Salary}");

    }

}

class Program

{

    static void Main(string[] args)

    {

        Staff staff1 = new Staff(101, "Michael", 890000);

        Staff staff2 = new Staff(102, "Stuart", 59000);

        staff1.ShowInfo();

        staff2.ShowInfo();

    }

}

Output:

Output

101  Michael  890000

102  Stuart  59000

Explanation:

In this instance, we define a class called Employee with three attributes: EmployeeId, EmployeeName, and EmployeeSalary. Subsequently, a constructor is implemented that takes three arguments. Following this, the ShowDetails function is added to exhibit the EmployeeId, EmployeeName, and EmployeeSalary. Within the main function, two instances, employee1 and employee2, are instantiated and assigned values. Finally, the ShowDetails function is invoked to exhibit the information regarding the employees.

Uses of this keyword in C#

There are several uses of this keyword in C#. Some of them are as follows.

  • It is used to pass the reference of the current object to another method.
  • It is used to access the members of the current class.
  • It is used to invoke the constructor.
  • It is used to define and apply the extension methods.
  • Characteristics of this keyword in C#

In C#, several characteristics of this keyword are as follows:

  • This keyword is automatically created during the execution of a member function.
  • Static functions do not allow this keyword in C#.
  • The 'this' keyword is not allowed in static functions because static members belong to the class itself, not to any instance.
  • Different ways to use this keyword

There exist multiple methods to utilize this keyword in C#. A few examples include:

1) Accessing Data Members

In C#, the 'this' keyword is employed to resolve naming conflicts that arise when a method parameter shares the same name as a member variable of an object.

Accessing Data Members Example using this keyword

Let's consider an example to illustrate how we can retrieve data members by utilizing the 'this' keyword in C#.

Example

Example

using System;

class Sample

{

    private int number;

    public void AssignValue(int number)

    {

        this.number = number; // Resolves naming conflict

    }

    public void Display()

    {

        Console.WriteLine("Value of number: " + number);

    }

    static void Main()

    {

        Sample obj = new Sample();

        obj.AssignValue(10);

        obj.Display();

    }

}

Output:

Output

Value of number: 10

Explanation:

In this instance, we define a Demo class that includes a private integer instance variable and two functions, SetValue and Show. The SetValue function updates the value of a variable utilizing the 'this' keyword. Within the primary function, we instantiate an object, set the values, and subsequently invoke the Show function to display the outcome.

2) Returning the Object (Method Chaining)

In C#, the practice of invoking several methods within a single object in a sequential manner is referred to as method chaining. The utilization of the this keyword is essential for facilitating method chaining as it provides access to the current class instance.

Returning the Object Example using this keyword

Let's consider an example to demonstrate the technique of method chaining in C#.

Example

Example

using System;

class point

{

    private int val;

    public point Set_Val(int x)

    {

        this.val = x;

        return this; // Return the current object

    }

    public void Display()

    {

       Console.WriteLine("The value is " + val);

    }

}

class Program

{

    static void Main()

    {

        point obj = new point(); // creating an object

        obj.Set_Val(25).Display(); 

    }

}

Output:

Output

The value is 25

Explanation:

In this instance, we are establishing a Chain class that includes a private integer data field along with two functions, SetValue and Display. Subsequently, the SetValue function utilizes the this keyword to deliver the current object, enabling method chaining. Ultimately, this facilitates the invocation of several functions on a singular object within one instruction, enhancing the clarity and flow of the code.

3) Passing the Current Object in C#

In C#, the this keyword is employed to denote the present instance of the class. It is utilized to transmit the current object as a parameter to a method or constructor.

Passing the Current Object Example utilizing the 'this' keyword

Let's examine a demonstration to showcase how we can transmit the existing objects by utilizing the 'this' keyword in C#.

Example

Example

using System;

class Simple

{

    public void Show()

    {

        Console.WriteLine("Inside show method");

    }

    public void Called(Simple obj)

    {

        obj.Show(); // Calling Show() method

    }

    public void Exec()

    {

        Called(this); // Passing the current object

    }

    static void Main()

    {

        Simple s = new Simple();

        s.Exec(); 

    }

}

Output:

Output

Inside Show method

Explanation:

In this instance, we introduce the Demo class that comprises three functions: Display, Invoke, and Perform. The Display function employs the Console.WriteLine method to exhibit the content. The Invoke function accepts an instance of the class as an argument and triggers its Display function. Within the Perform function, this action is utilized to transfer the existing instance to the Invoke function. Subsequently, we instantiate the Demo class object and invoke the perform operation.

Using this keyword in a Constructor in C#

In C#, the this keyword is employed within a constructor to refer to the current instance of the class. This allows for the invocation of another constructor within the class itself.

Constructor Example using this keyword

Let's consider an example to resolve naming conflicts in the constructor by utilizing the 'this' keyword in C#.

Example

Example

using System;

class Sample

{

    private int number;

    // Constructor using 'this' keyword to resolve name conflict

    public Sample(int number)

    {

        this.number = number;

        Console.WriteLine("Constructor executed. Initial number: " + this.number);

    }

    // Method chaining using 'this' keyword

    public Sample UpdateNumber(int value)

    {

        this.number = value;

        return this;

    }

    public void Show()

    {

        Console.WriteLine("Updated Number: " + number);

    }

    static void Main()

    {

        Sample obj = new Sample(10);     // object

        obj.UpdateNumber(20).Show();     //updates number 

    }

}

Output:

Output

Constructor executed. Initial number: 10

Updated Number: 20

Explanation:

In this instance, we establish a Demo class that includes a private integer attribute and two functions: ModifyValue and Display. The Demo initializer assigns the initial value of the integer using the this keyword to handle a name clash. The ModifyValue function is employed to alter the integer's value, while the Display function is utilized to exhibit the adjusted integer value. Within the Start function, we instantiate an object, define its value, and exhibit it through method chaining.

Conclusion

In summary, the 'this' keyword in the C# programming language points to the present instance of the class. Its primary purpose is to access members within the class, including instance members and the constructor. This keyword is employed for passing the current object as an argument to another function, enhancing code clarity, and enabling method chaining by returning the current object.

C# this Keyword FAQs

1) What is this keyword in C#?

In C#, the 'this' keyword denotes the present instance of the class. Its primary purpose is to access instance elements such as fields, methods, and properties. 'this' is employed to disambiguate naming clashes within the codebase.

Is it permissible to use this keyword in static methods within C# programming?

No, this particular keyword cannot be employed within static methods in C# due to their association with the class.

3) Is it possible to pass this keyword as an argument in C#?

Yes, we can pass the this keyword as an argument.

4) Is this a pointer in C#?

No, this is the keyword in C#.

5) Where can this keyword be used in C#?

In C# programming, the 'this' keyword is employed to invoke one constructor from another, transmit the current object as an argument, resolve naming clashes between fields and parameters, and facilitate method chaining by returning the current object.

Input Required

This code uses input(). Please provide values below: