CHAPTER 13 UNDERSTANDING OBJECT LIFETIME
return string.Format("{0} is going {1} MPH",
PetName, CurrentSpeed);
}
}
After a class has been defined, you may allocate any number of objects using the C# new keyword.
Understand, however, that the new keyword returns a reference to the object on the heap, not the actual
object itself. If you declare the reference variable as a local variable in a method scope, it is stored on the
stack for further use in your application. When you want to invoke members on the object, apply the C#
dot operator to the stored reference, like so:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** GC Basics *****");
// Create a new Car object on
// the managed heap. We are
// returned a reference to this
// object ("refToMyCar").
Car refToMyCar = new Car("Zippy", 50);
}
// The C# dot operator (.) is used
// to invoke members on the object
// using our reference variable.
Console.WriteLine(refToMyCar.ToString());
Console.ReadLine();
}
Figure 13-1 illustrates the class, object, and reference relationship.
Figure 13-1. References to objects on the managed heap
Note Recall from Chapter 4 that structures are value types that are always allocated directly on the stack and
are never placed on the .NET managed heap. Heap allocation occurs only when you are creating instances of classes.
474