The this Keyword

The keyword this refers to the current instance of an object. The this reference is a hidden parameter in every nonstatic method of a class (static methods are discussed later in this chapter). There are three ways in which the this reference is typically used. The first way is to qualify instance members that have the same name as parameters, as in the following:

    public void SomeMethod (int hour)
    {
     this.hour = hour;
    }

In this example, SomeMethod( ) takes a parameter (hour) with the same name as a member variable of the class. The this reference is used to resolve the ambiguity. While this.hour refers to the member variable, hour refers to the parameter.

You can, for example, use the this reference to make assigning to a field more explicit:

    public void SetTime(
        year, month, date, newHour, newMinute, newSecond)
    {
         this.year = year;         // use of "this" required
         this.month = month;       // required
         this.date = date;         // required
         this.hour = hour;         // use of "this" optional
         this.minute = newMinute;  // optional
         second = newSecond;       // also ok
    }

If the name of the parameter is the same as the name of the member variable, then you must use the this reference to distinguish between the two, but if the names are different (such as newMinute and newSecond), then the use of the this reference is optional.

Tip

The argument in favor of naming the argument to a method the same as the name of the member is that the relationship between the two is made explicit. The counterargument is that using the same name for both the parameter and the member variable can be confusing as to which one you are referring to at any given moment.

The second use of the this reference is to pass the current object as a parameter to another method, as in the following code:

    Class SomeClass
    {
         public void FirstMethod(OtherClass otherObject)
         {
              otherObject.SecondMethod(this);
         }
         // ...
    }

This code snippet establishes two classes, SomeClass and OtherClass. SomeClass has a method named FirstMethod( ), and OtherClass has a method named SecondMethod( ).

Inside FirstMethod( ), we’d like to invoke SecondMethod( ), passing in the current object (an instance of SomeClass) for further processing. To do so, you pass in the this reference, which refers to the current instance of SomeClass.

The third use of this is with indexers, which are covered in Chapter 12.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset