Chapter 8 Object-Based Programming (My web site) 311 Testing and Debugging

Chapter 8 Object-Based Programming 311 Testing and Debugging Tip 8.2 Avoid method-parameter names (or local variable names) that conflict with instance variable names to prevent subtle, hard-to-trace bugs. Good Programming Practice 8.6 The explicit use of the this reference can increase program clarity in some contexts where this is optional. Class ThisTest(Fig. 8.12) runs the application that demonstrates explicit use of the this reference. Line 13 instantiates an instance of class Time4. Lines 15 16 invoke method BuildStringof the Time4object, then display the results to the user in a MessageBox. The problem of parameters (or local variables) hiding instance variables can be solved by using properties. If we have a property Hourthat accesses the hourinstance variable, then we would not need to use this.hourto distinguish between a parameter (or local variable) hourand the instance variable hour we would simply assign hourto Hour. 8.10 Garbage Collection In previous examples, we have seen how a constructor initializes data in an object of a class after the object is created. Operator newallocates memory for the object, then calls that object s constructor. The constructor might acquire other system resources, such as network connections and databases or files. Objects must have a disciplined way to return memory and release resources when the program no longer uses those objects. Failure to release such resources causes resource leaks potentially exhausting the pool of available resources that programs might need to continue executing. 1 // Fig. 8.12: ThisTest.cs 2 // Using the this reference. 3 4 using System; 5 using System.Windows.Forms; 6 7 // ThisTest class definition 8 class ThisTest 9 { 10 // main entry point for application 11 static void Main( string[] args ) 12 { 13 Time4 time = new Time4( 12, 30, 19 ); 14 15 MessageBox.Show( time.BuildString(), 16 “Demonstrating the “this” Reference” ); 17 } 18 } Fig. 8.12 Fig. 8.12Fig. 8.FiFi12g. 8.12g. 8.12thisreference demonstration. (Part 1 of 2.)
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Leave a Reply