Referring to the Current Objects Members with the this Reference

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 is called for a particular object, the method's body implicitly uses keyword this to refer to the object's instance variables and other methods. As you will see in Fig. 9.4, you can also use keyword this explicitly in a non-static method's body. Section 9.5 and Section 9.6 show two more interesting uses of keyword this. Section 9.10 explains why keyword this cannot be used in a static method.

Figure 9.4. this used implicitly and explicitly to refer to members of an object.

1 // Fig. 9.4: ThisTest.cs 2 // this used implicitly and explicitly to refer to members of an object. 3 using System; 4 5 public class ThisTest 6 { 7 public static void Main( string[] args ) 8 { 9 SimpleTime time = new SimpleTime( 15, 30, 19 ); 10 Console.WriteLine( time.BuildString() ); 11 } // end Main 12 } // end class ThisTest 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 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 } // end SimpleTime constructor 30 31 // use explicit and implicit "this" to call ToUniversalString 32 public string BuildString() 33 { 34 return string.Format( "{0,24}: {1} {2,24}: {3}", 35 "this.ToUniversalString()", this.ToUniversalString(), 36 "ToUniversalString()", ToUniversalString() ); 37 } // end method BuildString 38 39 // convert to string in universal-time format (HH:MM:SS) 40 public string ToUniversalString() 41 { 42 // "this" is not required here to access instance variables, 43 // because method does not have local variables with same 44 // names as instance variables 45 return string.Format( "{0:D2}:{1:D2}:{2:D2}", 46 this.hour, this.minute, this.second ); 47 } // end method ToUniversalString 48 } // end class SimpleTime

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

We now demonstrate implicit and explicit use of the this reference to enable class ThisTest's Main method to display the private data of a class SimpleTime object (Fig. 9.4). For the sake of brevity, we declare two classes in one fileclass ThisTest is declared in lines 512, and class SimpleTime is declared in lines 1548.

Class SimpleTime (lines 1548) declares three private instance variableshour, minute and second (lines 1719). The constructor (lines 2429) receives three int arguments to initialize a SimpleTime object. Note that for the constructor we used parameter names that are identical to the class's instance variable names (lines 1719). We don't recommend this practice, but we did it here to hide the corresponding instance variables so that we could illustrate explicit use of the this reference. Recall from Section 7.11 that if a method contains a local variable with the same name as a field, that method will refer to the local variable rather than the field. In this case, the local variable hides the field in the method's scope. However, the method can use the this reference to refer to the hidden instance variable explicitly, as shown in lines 2628 for SimpleTime's hidden instance variables.

Method BuildString (lines 3237) returns a string created by a statement that uses the this reference explicitly and implicitly. Line 35 uses the this reference explicitly to call method ToUniversalString. Line 36 uses the this reference implicitly to call the same method. Note that both lines perform the same task. Programmers typically do not use the this reference explicitly to reference other methods in the current object. Also, note that line 46 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.

Common Programming Error 9 2

It is often a logic error when a method contains a parameter or local variable that has the same name as an instance variable of the class. In such a case, use reference this if you wish to access the instance variable of the classotherwise, the method parameter or local variable will be referenced.

Error Prevention Tip 9 1

Avoid method parameter names or local variable names that conflict with field names. This helps prevent subtle, hard-to-locate bugs.

Class ThisTest (Fig. 9.4, lines 512) 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.

Performance Tip 9 1

C# conserves memory by maintaining only one copy of each method per classthis method is invoked by every object of the class. Each object, on the other hand, has its own copy of the class's instance variables (i.e., non-static variables). Each method of the class implicitly uses the this reference to determine the specific object of the class to manipulate.

Indexers

Категории