10.4 Referring to the Current Object’s Members with the this Reference

Every object can access a reference to itself with keyword this (also called the this reference). When a non-static method (or property) is called for a particular object, the method’s body implicitly uses keyword this to refer to the object’s instance variables and other non-static class members. As you’ll see in Fig. 10.4, you also can use keyword this explicitly in a non-static method’s body. Section 10.5 shows a more interesting use of keyword this. Section 10.9 explains why keyword this cannot be used in a static method.

Fig. 10.4 this used implicitly and explicitly to refer to members of an object.

Alternate View

 1    // Fig. 10.4: ThisTest.cs
 2    // this used implicitly and explicitly to refer to members of an object.
 3    using System;
 4
 5    class ThisTest
 6    {
 7       static void Main()
 8       {
 9          var time = new SimpleTime(15, 30, 19);
10          Console.WriteLine(time.BuildString());
11       }
12    }
13
14    // class SimpleTime demonstrates the "this" reference
15    public class SimpleTime
16    {
17       private int hour; // 0-23
18       private int minute; // 0-59
19       private int second; // 0-59
20
21        // if the constructor uses parameter names identical to
22        // instance-variable names, the "this" reference is
23        // required to distinguish between the names
24       public SimpleTime(int hour, int minute, int second)
25       {
26          this.hour = hour; // set "this" object's hour instance variable
27          this.minute = minute; // set "this" object's minute            
28          this.second = second; // set "this" object's second            
29       }
30
31       // use explicit and implicit "this" to call ToUniversalString
32       public string BuildString() =>
33          $"{"this.ToUniversalString()",24} :  {this.ToUniversalString()}" +
34          $"
{"ToUniversalString()",24}: {ToUniversalString():}} ";
35
36       // convert to string in universal-time format (HH:MM:SS);
37       // "this" is not required here to access instance variables,
38       // because the method does not have local variables with the same
39       // names as the instance variables
40       public string ToUniversalString() =>
41          $"{this.hour: D2} : {this.minute:D2} : {this.second :D2}";
42    }

this.ToUniversalString(): 15:30:19
     ToUniversalString(): 15:30:19

Figure 10.4 demonstrates implicit and explicit use of the this reference to enable class ThisTest’s Main method to display the private data of a SimpleTime object. For the sake of brevity, we declare two classes in one file—class ThisTest is declared in lines 5–12, and class SimpleTime is declared in lines 15–42.

Class SimpleTime declares three private instance variables—hour, minute and second (lines 17–19). The constructor (lines 24–29) receives three int arguments to initialize a SimpleTime object (without validation for simplicity). Here, we used parameter names that are identical to the class’s instance-variable names (lines 17–19). We did this intentionally to hide the corresponding instance variables so that we could illustrate explicit use of the this reference. If a method contains a local variable with the same name as an instance variable, the local variable is said to shadow (or hide) the instance variable in the method’s body. However, you can use this to access the hidden instance variable explicitly, as shown in lines 26–28 for SimpleTime’s hidden instance variables.

Software Engineering Observation 10.4

Using properties throughout a class to access the class’s instance variables normally eliminates shadowing because property names use Pascal Case naming (capital first letter) and parameter names use Camel Case (lowercase first letter).

Method BuildString (lines 32–34) returns a string created by a statement that uses the this reference explicitly and implicitly. Line 33 uses the this reference explicitly to call method ToUniversalString. Line 34 uses the this reference implicitly to call the same method. Programmers typically do not use the this reference explicitly to reference other methods in the current object. Also, line 41 in method ToUniversalString explicitly uses the this reference to access each instance variable. This is not necessary here, because the method does not have any local variables that hide the instance variables of the class.

Class ThisTest (lines 5–12) demonstrates class SimpleTime. Line 9 creates an instance of class SimpleTime and invokes its constructor. Line 10 invokes the object’s BuildString method, then displays the results.

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

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