Chapter 11. Captain Amazing: The Death of the Object
The life and death of an object
Here’s a quick review of what we know about how objects live and die:
When you create an object, the CLR—which runs your .NET applications and manages memory—allocates enough memory for it on the heap, a special portion of your computer’s memory reserved for objects and their data.
It’s kept “alive” by a reference, which can be stored in a variable, a collection, or a property or field of another object.
There can be lots of references to the same object—like you saw in Chapter 4, when you pointed the
lloyd
andlucinda
reference variables to the same instance of Elephant.When you took away the last reference to the Elephant object, that caused the CLR to mark it for garbage collection.
And eventually the CLR removed the Elephant object and the memory was reclaimed so it could be used for new instances of objects that your program would go on to create later.
Now we’ll explore all of these points in more detail, writing small programs that help show how garbage collection works.
But ...
Get Head First C#, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.