C# - 'this' Keyword

Learn about the C# 'this' keyword with the help of examples.
[Last updated : March 21, 2023]

The 'this' Keyword in C#

In C#.Net 'this' is a reference of current object, which is accessible within the class only.

To access an element of class by referencing current object of it, we use this keyword, remember following points:

  1. this keyword is used.
  2. this cannot be used with the static member functions.

'this' Keyword Example in C#

The below program demonstrates the example 'this' keyword.

C# program to demonstrate the example of 'this' keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {

  class Sample {
    private int a;
    private int b;

    public Sample() {
      a = 0;
      b = 0;
    }

    public void setValues(int a, int b) {
      this.a = a;
      this.b = b;
    }
    public void printValues() {
      Console.WriteLine("A: " + a + " B: " + b);
    }

  }
  class Program {
    static void Main(string[] args) {
      Sample S;

      S = new Sample();

      S.setValues(10, 20);
      S.printValues();

      Console.WriteLine();

    }
  }
}

Output

A: 10 B: 20

Explanation

In above program within setValues() method, this is used to differentiate between data member of class and local variable of method. Because this is a reference of current class object it can be used as data member.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.