CHAPTER 13 UNDERSTANDING OBJECT LIFETIME
private Lazy allSongs = new Lazy();
}
public AllTracks GetAllTracks()
{
// Return all of the songs.
return allSongs.Value;
}
Beyond the fact that we are now representing the AllTracks member variable as a Lazy<> type,
notice that the implementation of the previous GetAllTracks() method has also been updated.
Specifically, we must make use of the read-only Value property of the Lazy<> class to obtain the actual
stored data (in this case, the AllTracks object that is maintaining the 10,000 Song objects).
With this simple update, notice how the following updated Main() method will indirectly allocate
the Song objects only if GetAllTracks() is indeed called:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Lazy Instantiation *****\n");
// No allocation of AllTracks object here!
MediaPlayer myPlayer = new MediaPlayer();
myPlayer.Play();
// Allocation of AllTracks happens when you call GetAllTracks().
MediaPlayer yourPlayer = new MediaPlayer();
AllTracks yourMusic = yourPlayer.GetAllTracks();
Console.ReadLine();
}
Note Lazy object instantiation is not only useful to decrease allocation of unnecessary objects. You can also use
this technique if a given member has expensive creation code, such as invoking a remote method, communication
with a relational database, or whatnot.
Customizing the Creation of the Lazy Data
When you declare a Lazy<> variable, the actual i