Sunday, November 16, 2008

The Basics of Object Lifetime in C#.NET

While building your C# applications, you can feel free to assume that the managed heap will take care of itself without your direct intervention. In fact, memory management is one of those things which power the .NET platform. The golden rule of .NET memory management is quite simple:Rule: Allocate an object onto the managed heap using the new keyword and forget about it.Once “new-ed”, the garbage collector will destroy the object when it is no longer needed. The next question obviously rises, of course, is, “How does the garbage collector determine when an object is no longer needed?" The incomplete but short answer is that the garbage collector removes an object from theheap when it is unreachable by any part of your code base. Look at the following code, you have a method that allocates a local Car object:

public static void MakeACar()
{
// If myCar is the only reference to the Car object,
// it may be destroyed when the method returns
Car myCar = new Car();
//...
}

Notice that the Car reference (myCar) has been created directly within the MakeACar() method and has not been passed outside of the defining scope (via a return value or ref/out parameters). Thus, once this method call completes, the myCar reference is no longer reachable. And this makes the associated Car object a candidate for garbage collection. However, it is not guaranteed that this object will be reclaimed from memory immediately after MakeACar() has completed. All you can assume at this point is that when the CLR(Common Language Runtime) performs the next garbage collection, the myCar object could be(not must be) safely destroyed.As you will most certainly discover, programming in a garbage-collected environment will greatly simplify your application development. In stark contrast, C++ programmers are painfully aware that if they fail to manually delete heap-allocated objects, memory leaks are never far behind. In fact, tracking down memory leaks is one of the most time-consuming (and tedious) aspects of programming with unmanaged languages. By allowing the garbage collector to be in charge of destroying objects, the burden of memory management has been taken from your shoulders and placed onto those of the CLR.

No comments: