The Role of the ‘this’ Keyword

Instance (non-static) methods can only be invoked on an existing object.  Within any instance method (including
constructors), you can refer to the current object using the
this keyword.  In fact, whenever you access another
instance member, you are implicitly using the
this keyword.  You cannot use this, either explicitly or implicitly,
from within a static member.


public class Employee
{
  private double mWage;
  private string mName;
  private double mHours;

  public double ComputePay()
  {
     double pay;

     // Using implicit this.

     pay = mWage * mHours;

     // This line is the same as above.

     pay = this.mWage * this.mHours;
     return pay;
  }
...
}



The this keyword can be used to distinguish between class fields and incoming parameters or local variables.  By
convention, each field name is prefixed with “m” to indicate it is a class member.  However, some coding styles
don’t allow this convention. Consider the following employee class:


public class Employee
{

  // Class fields. Note: No m prefix.

  private double wage;
  private string name;
  private double hours;

  public Employee(string name, double wage, double hours)
  {

     // Use 'this' to distinguish between class fields and params.

     this.name = name;
     this.wage = wage;
     this.hours = hours;
  }
...
}



You can also use the this keyword to force one constructor to call another.  Consider this example:


public class Employee
{

  // If the user calls this constructor, forward to the 3-arg
  // version.

  public Employee(string name)
     : this(name, 0.0, 0.0) // Note the colon (:). This is similar
  {}                        // to C++ member initialization syntax.

  public Employee(string name, double wage, double hours)
  {
     // Use 'this' to distinguish between class fields and params.
     this.name = name;
     this.wage = wage;
     this.hours = hours;
  }
...
}
this Keyword
Table of Contents
C# Tutorial | C#.NET Tutorial | Read-Only Members Tutorial

Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used
exclusively as an online learning aid.  Any attempts to copy, reproduce, or use for training is
strictly prohibited.
Courseware
Training Resources
Tutorials
Services