.NET Documentation

Object Lifetimes in .NET

Understanding how the .NET runtime manages the lifetime of objects is essential for writing efficient, reliable applications. This article covers the phases an object goes through from allocation to reclamation.

1. Allocation

When you create an instance with new, the runtime allocates memory from the managed heap. The size of the object is determined by its fields and runtime overhead.


class Customer
{
    public string Name { get; set; }
    public int Id { get; set; }
}
var c = new Customer(); // allocation on the managed heap
        

2. Reachability

An object is considered reachable if it can be accessed directly or indirectly from a root reference (e.g., static fields, local variables on the stack, or CPU registers).

3. Garbage Collection

When no root references point to an object, it becomes unreachable. The garbage collector (GC) periodically scans the heap, identifies unreachable objects, and reclaims their memory.

Read more about GC in Garbage Collection.

4. Finalization

If a class implements a finalizer, the GC places the object on the finalization queue before reclaiming its memory, giving it a chance to release unmanaged resources.


class UnmanagedWrapper
{
    ~UnmanagedWrapper()
    {
        // Release native handles here
    }
}
        

See Finalizers for details and best practices.

5. Dispose Pattern

For deterministic cleanup of unmanaged resources, implement IDisposable and call Dispose() manually or via a using statement.


using (var file = new FileStream(path, FileMode.Open))
{
    // work with the file
} // Dispose called automatically
        

More on the dispose pattern here.

6. Weak References

A WeakReference allows you to hold a reference to an object without preventing its collection. This is useful for caches.


var cache = new WeakReference<Customer>(customer);
if (cache.TryGetTarget(out var cachedCustomer))
{
    // use cachedCustomer
}
        

Read about weak references in Weak References.

Best Practices

Related Articles