#923 – An Object Isn’t Necessarily Deleted as Soon as It’s Dereferenced

An object will typically be deleted, and its memory reclaimed, at some point after the object is no longer being referenced by any reference-typed variables.

The object won’t necessarily be deleted when you stop referencing it.  The garbage collector will only delete the object when it needs to reclaim some space in memory.  We refer to this as nondeterministic destruction–the idea that we can’t predict when an object will be destroyed.

            // myDog references a Dog object
            Dog myDog = new Dog("Kirby");

            // Set reference to null, so that we
            // no longer reference "Kirby" Dog object.
            myDog = null;

            // "Kirby" won't necessarily have been
            // destroyed at this point

#732 – Destruction vs. Collection

Automatic memory management in C# means that the memory for a heap-based object is automatically released when there is no longer any user-written code that references the object.  This is done by the garbage collector.

An object goes through two distinct phases when it is no longer referenced–destruction and collection.

When an object is no longer referenced by any user-written code, other than code in a destructor, the object becomes eligible for destruction.

Once the object is eligible for destruction, it may be destructed at some point in the future, i.e. its destructor is called.

After the object is destructed and it is no longer being referenced by any code, including code in a destructor, the object becomes eligible for collection.

Once the object is eligible for collection, the garbage collector may at some point in the future release memory for the object.

#425 – Nondeterministic Destruction and Object Finalization

In .NET, the CLR (Common Language Runtime) is responsible for reclaiming memory for objects that are no longer being referenced, through garbage collection.

Garbage collection can be done on an object as soon as it’s no longer being referenced by any other objects.  However, the garbage collector may not free memory for an object immediately.  It can choose to free up memory for an object whenever it likes.

Every object has a Finalize method that you can override, which will be called when the object is being destroyed.  This method allows cleaning up any unmanaged resources the object might hold, before the object is destroyed.

The CLR implements nondeterministic destruction–you can’t explicitly force an object’s Finalize method to be called and you can’t predict when it is called.  There’s also no guarantee that the finalizer will ever be called–an application might crash before the finalizer is called.