C H A P T E R 13
Understanding Object Lifetime
At this point in the text, you have learned a great deal about how to build custom class types using C#.
Now you will see how the CLR manages allocated class instances (a.k.a. objects) via garbage collection.
C# programmers never directly deallocate a managed object from memory (recall there is no delete
keyword in the C# language). Rather, .NET objects are allocated to a region of memory termed the
managed heap, where they will be automatically destroyed by the garbage collector “sometime in the
future.”
After you have looked at the core details of the collection process, you’ll learn how to
programmatically interact with the garbage collector using the System.GC class type (which is something
you will typically not be required to do for a majority of your .NET projects). Next, you’ll examine how
the virtual System.Object.Finalize() method and IDisposable interface can be used to build classes
that release internal unmanaged resources in a predictable and timely manner.
You will also delve into some new functionality of the garbage collector introduced with .NET 4.0,
including background garbage collections and lazy instantiation using the generic System.Lazy<> class.
By the time you have completed this chapter, you will have a solid understanding of how .NET objects
are managed by the CLR.
Classes, Objects, and References
To frame the topics covered in this chapter, it is important to further clarify the distinction between
classes, objects, and reference variables. Recall that a class is nothing more than a blueprint that
describes how an instance of this type will look and feel in memory. Classes, of course, are defined
within a code file (which in C# takes a *.cs extension by convention). Consider the following simple Car
class defined within a new C# Console Application project named SimpleGC:
// Car.cs
public class Car
{
public int CurrentSpeed {get; set;}
public string PetName {get; set;}
public Car(){}
public Car(string name, int speed)
{
PetName = name;
CurrentSpeed = speed;
}
public override string ToString()
{
473