Free mag vol1 | Page 544

CHAPTER 13  UNDERSTANDING OBJECT LIFETIME explicit request for a garbage collection (via the GC.Collect() method), the CLR performed a number of them in the background. ***** Fun with System.GC ***** Estimated bytes on heap: 70240 This OS has 3 object generations. Zippy is going 100 MPH Generation of refToMyCar is: 0 Generation of refToMyCar is: 1 Generation of tonsOfObjects[9000] is: 1 Gen 0 has been swept 1 times Gen 1 has been swept 0 times Gen 2 has been swept 0 times At this point, I hope you feel more comfortable regarding the details of object lifetime. In the next section, we’ll examine the garbage collection process a bit further by addressing how you can build finalizable objec ts, as well as disposable objects. Be very aware that the following techniques are typically necessary only if you are building C# classes that maintain internal unmanaged resources.  Source Code The SimpleGC project is included under the Chapter 13 subdirectory. Building Finalizable Objects In Chapter 6, you learned that the supreme base class of .NET, System.Object, defines a virtual method named Finalize(). The default implementation of this method does nothing whatsoever: // System.Object public class Object { ... protected virtual void Finalize() {} } When you override Finalize() for your custom classes, you establish a specific location to perform any necessary cleanup logic for your type. Given that this member is defined as protected, it is not possible to directly call an object’s Finalize() method from a class instance via the dot operator. Rather, the garbage collector will call an object’s Finalize() method (if supported) before removing the object from memory. 485