Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using the this Keyword

You can obtain the reference to a class from within instance members that belong to the class. To indicate explicitly that the field or method accessed is an instance member of the containing class in C#, you use the keyword this. Use of this is implicit when calling any instance member, and it returns an instance of the object itself.

For example, consider the SetName() method shown in Listing 5.9.

LISTING 5.9: Using this to Identify the Field’s Owner Explicitly

class Employee
{
  public string FirstName;
  public string LastName;
  public string Salary;
 
  public string GetName()
  {
      return $"{ FirstName }  { LastName }";
  }
 
  public void SetName(                                                          
      string newFirstName, string newLastName)                                  
  {                                                                             
      this.FirstName = newFirstName;                                            
      this.LastName = newLastName;                                              
  }                                                                             
}

This example uses the keyword this to indicate that the fields FirstName and LastName are instance members of the class.

Although the this keyword can prefix any and all references to local class members, the general guideline is not to clutter code when there is no additional value. Therefore, you should avoid using the this keyword unless it is required. Listing 5.12 (later in this chapter) is an example of one of the few circumstances when such a requirement exists. Listings 5.9 and 5.10, however, are not good examples. In Listing 5.9, this can be dropped entirely without changing the meaning of the code. And in Listing 5.10 (presented next), by changing the naming convention for fields, we can avoid any ambiguity between local variables and fields.

In Listing 5.9 and Listing 5.10, the this keyword is not used in the GetName() method—it is optional. However, if local variables or parameters exist with the same name as the field (see the SetName() method in Listing 5.10), omitting this would result in accessing the local variable/parameter when the intention was the field; given this scenario, use of this is required.

You also can use the keyword this to access a class’s methods explicitly. For example, this.GetName() is allowed within the SetName() method, permitting you to print out the newly assigned name (see Listing 5.11 and Output 5.3).

LISTING 5.11: Using this with a Method

class Employee
{
  // ...
 
  public string GetName()
  {
      return $"{ FirstName }  { LastName }";
  }
 
  public void SetName(string newFirstName, string newLastName)
  {
      this.FirstName = newFirstName;
      this.LastName = newLastName;
      Console.WriteLine(                                                          
          $"Name changed to '{ this.GetName() }'");                               
  }
}
__________________________________________________________________________________

class Program
{
  static void Main()
  {
      Employee employee = new Employee();
 
      employee.SetName("Inigo", "Montoya");
      // ...
  }
  // ...
}

OUTPUT 5.3

Name changed to 'Inigo Montoya'                                                   

Sometimes it may be necessary to use this to pass a reference to the currently executing object. Consider the Save() method in Listing 5.12.

LISTING 5.12: Passing this in a Method Call

class Employee
{
  public string FirstName;
  public string LastName;
  public string Salary;
 
  public void Save()
  {
      DataStorage.Store(this);                                                    
  }
}

__________________________________________________________________________________
class DataStorage
{
  // Save an employee object to a file
  // named with the Employee name.
  public static void Store(Employee employee)
  {
      // ...
  }
}

The Save() method in Listing 5.12 calls a method on the DataStorage class, called Store(). The Store() method, however, needs to be passed the Employee object, which needs to be persisted. This is done using the keyword this, which passes the instance of the Employee object on which Save() was called.

  • + Share This
  • 🔖 Save To Your Account