C#. Keyword this. The purpose of keyword this in class




Keyword this. The purpose of keyword this in class


Contents


Search other websites:

1. The definition of this keyword. What does the this keyword mean in the class?

Class methods can use the this keyword. By definition, this is an implicit reference to the current instance of the class, which has several useful uses in the class.

 

2. Cases of using the this keyword in C# programs

The keyword this is used in the following cases.

  1. When a name exists in a class method that matches the name of a class field.
  2. If there are several constructors in a class, then this is used to call the main constructor from others (redirecting to the main constructor). This is to avoid code duplication.
  3. When a method needs to pass a reference to the current object. In this case, when calling the method, the this keyword is indicated.
  4. If an indexer is declared in the class.

 

3. An example of using this to access class fields from a method body

In the example, two methods and two constructors are declared in the Program class:

  • constructor Program() without parameters;
  • constructor Program() with one parameter. This constructor demonstrates using this to initialize a class field;
  • method PrintInt() – demonstrates access to the field of the class whose name is overlapped by the name of the method parameter;
  • method Print() – demonstrates access to a field of a class whose name is overlapped by the name of the internal variable declared in the method.

The program text is as follows

using System;
using static System.Console; // include the static class System.Console

namespace ConsoleApp2
{
  // Keyword this. Access to class fields from a method.
  class Program
  {
    int d = 25; // class field named d

    // constructor without parameters
    Program()
    {
    }

    // Constructor with 1 parameter, the name of parameter - d
    Program(int d)
    {
      this.d = d; // use this to access the field d
    }

    // A function that displays the value of the parameter and field d
    public void PrintInt(int d) // parameter name d matches the field name d
    {
      // Access to the parameter d
      WriteLine("Parameter d = {0}", d);

      // Access to the field d by referring this.d
      WriteLine("Field d = {0}", this.d); // Field d = 25
    }

    // A function in which an internal variable named d is declared
    public void Print()
    {
      // Internal variable d - the name of this variable matches the name of the field d
      int d = 77;

      // Print the value of the internal variable d
      WriteLine("Internal d = {0}", d);

      // Access to field d is implemented as this.d
      WriteLine("Field d = {0}", this.d); // Field d = 25
    }

    static void Main(string[] args)
    {
      // Demonstrates the use of the this keyword
      // 1. Declare an instance of the Program class
      Program pr = new Program(30); // constructor call with 1 parameter

      // 2. Call the PrintInt() method
      pr.PrintInt(50);

      // 3. Call the Print() method
      pr.PrintD();
    }
  }
}

The result of the program

Parameter d = 50
Field d = 30
Internal d = 77
Field d = 30

 

4. An example of using this to call class constructors

The keyword this can be used to call one constructor from another constructor. For a class that contains several constructors, the main constructor is selected. This is the constructor with the most parameters. Other constructors access this main constructor by calling this.

The Line class is defined that defines the line given by the coordinates of the two extreme points (x1; y1), (x2; y2). The class demonstrates calling constructors using the this keyword.

In our case, the main constructor is a constructor with 4 parameters.

The text of the Line class is as follows:

using System;
using static System.Console; // include the static class System.Console

namespace ConsoleApp2
{
  // The keyword this. Call the class constructor
  class Line
  {
    private int x1, y1, x2, y2;

    // Main constructor: it has 4 parameters
    public Line(int x1, int y1, int x2, int y2)
    {
      // Using this to access fields
      this.x1 = x1;
      this.y1 = y1;
      this.x2 = x2;
      this.y2 = y2;
      WriteLine("Line(int, int, int, int)");
    }

    // Constructor with 2 parameters,
    // implements a line that starts from the origin.
    // The constructor uses the this keyword
    // to redirect to a constructor with 4 parameters.
    public Line(int x, int y) : this(0, 0, x, y)
    {
      WriteLine("Line(int, int)");
    }

    // Constructor without parameters, implements a line with coordinates (0; 0), (1; 1)
    public Line() : this(1, 1) // redirect to constructor with 2 parameters
    {
      WriteLine("Line()");
    }

    // Method that displays the fields x1, y1, x2, y2 on the screen
    public void Print()
    {
      WriteLine("Fields values: ");
      WriteLine($"x1 = {x1}, y1 = {y1}, x2 = {x2}, y2 = {y2}");
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // Demonstrate constructor calls with this
      WriteLine("Object l1:");
      Line l1 = new Line(1, 3, 5, 6);
      l1.Print();

      WriteLine("\nObject l2:");
      Line l2 = new Line(3, 4);
      l2.Print();

      WriteLine("\nObject l3:");
      Line l3 = new Line();
      l3.Print();
    }
  }
}

The result of the program

Object l1:
Line(int, int, int, int)
Fields values:
x1 = 1, y1 = 3, x2 = 5, y2 = 6

Object l2:
Line(int, int, int, int)
Line(int, int)
Fields values:
x1 = 0, y1 = 0, x2 = 3, y2 = 4

Object l3:
Line(int, int, int, int)
Line(int, int)
Line()
Fields values:
x1 = 0, y1 = 0, x2 = 1, y2 = 1


 

5. Passing a reference to the current object to the method. Example

If you need to pass the current instance of this class to the class method, then the this keyword is used. In the example below, the this keyword is used in the DisplayLengthOrigin() method of the Point class when calling the LengthOrigin() method of the same class.

The sample text for a Console Application is as follows:

using System;
using static System.Console; // include the static class System.Console

namespace ConsoleApp2
{
  // The keyword this. Passing a reference to the current object to the method
  class Point
  {
    int x, y;

    // Constructor with 2 parameters
    public Point(int x, int y)
    {
      this.x = x;
      this.y = y;
    }

    // Access methods
    double GetX() { return x; }
    double GetY() { return y; }
    void Set(int x) { this.x = x; }
    void Set(int y) { this.y = y; }

    // A method that calculates the distance from pt to the origin
    public double LengthOrigin(Point pt)
    {
      return Math.Sqrt(pt.GetX() * pt.GetX() + pt.GetY() * pt.GetY());
    }

    // This method uses this to pass the current instance
    // to the LengthOrigin() method.
    // The method displays the distance from the point to the origin
    public void DisplayLenthOrigin()
    {
      double len;

      // passing the current instance to the LengthOrigin() method
      len = LengthOrigin(this);

      WriteLine("The distance to the origin = {0:f3}", len);
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      Point pt = new Point(2, 5);
      pt.DisplayLenthOrigin();
    }
  }
}

The result of the program:

The distance to the origin = 5.385

 

6. An example of using the this keyword to declare an indexer

The example implements the ArrayIntegers class, which implements an array of integers. To access an array element, the indexers mechanism is used. The indexer uses the this keyword, which symbolizes a call to the current instance of the class. You can read more about the features of using indexers in classes here.

The demo text of the program created using the Console Application template is given below.

using System;
using static System.Console; // include the static class System.Console

namespace ConsoleApp2
{
  // Keyword this. Declarint an indexer
  class ArrayIntegers
  {
    private int[] Array; // a reference to array

    // Constructor with 1 parameter - main constructor
    // - size - array size;
    // - defaultValue - argument by default
    public ArrayIntegers(int size, int defaultValue = 0)
    {
      // 1. Checking for correct input
      if (size <= 0)
        size = 1; // at least 1 item in the array

      // 2. Allocate memory for Array
      Array = new int[size];

      // 3. Fill array with values by default
      for (int i = 0; i < Array.Length; i++)
        Array[i] = defaultValue;
    }

    // Constructor without parameters,
    // вызвать конструктор с 2 параметрами с помощью this
    public ArrayIntegers() : this(10, 0) // 10 items by default
    {
    }

    // Indexer - access to an array item by index,
    // this keyword is used here
    public int this[int index]
    {
      // accessors
      get
      {
        return Array[index];
      }

      set
      {
        Array[index] = value;
      }
    }

    // Method for displaying an array on the screen
    public void Print()
    {
      WriteLine("Array of integers:");
      for (int i = 0; i < Array.Length; i++)
        Write($"{Array[i]}\t");
      WriteLine();
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      // 1. Declare an instance of ArrayIntegers class
      ArrayIntegers AI = new ArrayIntegers(5);

      // 2. Initialize the AI array by values
      for (int i = 0; i < 5; i++)
        AI[i] = i * i;

      // 3. Display the array AI items
      AI.Print();
    }
  }
}

The result of the program:

Array of integers:
0 1 4 9 16

 

7. When can the this keyword not be used in a class?

The this keyword cannot be used:

  • in static class methods;
  • in static classes.

This is due to the fact that static methods exist only at the class level and are not related to class instances (class objects).

 


Related topics

 


 

0
fb-share-icon20