CHAPTER 13 UNDERSTANDING OBJECT LIFETIME
That concludes our investigation of how the CLR manages your objects via garbage collection. While
there are additional (somewhat esoteric) details regarding the collection process I haven’t covered here
(such as weak references and object resurrection), you are now in a perfect position for further
exploration on your own. To wrap this chapter up, we will examine a programming feature called “lazy
instantiation” of objects.
Understanding Lazy Object Instantiation
When you are creating classes, you might occasionally need to account for a particular member variable
in code, which might never actually be needed, in that the object user might not call the method (or
property) that makes use of it. Fair enough. However, this can be very problematic if the member
variable in question requires a large amount of memory to be instantiated.
For example, assume you are writing a class that encapsulates the operations of a digital music
player. In addition to the expected methods, such as Play(), Pause(), and Stop(), you also want to
provide the ability to return a collection of Song objects (via a class named AllTracks), which represents
every single digital music file on the device.
If you’d like to follow along, create a new Console Application named LazyObjectInstantiation, and
define the following class types:
// Represents a single song.
class Song
{
public string Artist { get; set; }
public string TrackName { get; set; }
public double TrackLength { get; set; }
}
// Represents all songs on a player.
class AllTracks
{
// Our media player can have a maximum
// of 10,000 songs.
private Song[] allSongs = new Song[10000];
public AllTracks()
{
// Assume we fill up the array
// of Song objects here.
Console.WriteLine("Filling up the songs!");
}
}
// The MediaPlayer has-an AllTracks object.
class MediaPlayer
{
// Assume these methods do something useful.
public void Play() { /* Play a song */ }
public void Pause() { /* Pause the song */ }
public void Stop() { /* Stop playback */ }
496