Object Lifetime

24.1 Garbage Collection Basics

.NET manages memory automatically. The Garbage Collector (GC) frees objects that are no longer reachable.

Generations (0, 1, 2) and the Large Object Heap. GC runs non-deterministically.

Unmanaged resources (files, DB connections, sockets, GDI handles) must be released explicitly with IDisposable.

24.2 The Using Statement

Using reader As New IO.StreamReader("data.txt")
    Console.WriteLine(reader.ReadToEnd())
End Using                       ' reader.Dispose() is called automatically, even on exceptions

Using conn As New SqlConnection(connStr), cmd As New SqlCommand("SELECT 1", conn)   ' multiple resources
    conn.Open()
    Console.WriteLine(cmd.ExecuteScalar())
End Using

24.3 Implementing IDisposable (Dispose Pattern)

Visual Studio generates this pattern when you type Implements IDisposable and press Enter.

IAsyncDisposable / Await Using aren't supported in VB syntax. Call DisposeAsync() manually.

Public Class ResourceHolder
    Implements IDisposable

    Private _stream As IO.FileStream
    Private _disposed As Boolean = False

    Public Sub New(path As String)
        _stream = New IO.FileStream(path, IO.FileMode.OpenOrCreate)
    End Sub

    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not _disposed Then
            If disposing Then
                _stream?.Dispose()          ' free managed resources
            End If
            ' free unmanaged resources here (if any)
            _disposed = True
        End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(disposing:=True)
        GC.SuppressFinalize(Me)
    End Sub

    ' Only if you hold unmanaged resources directly:
    ' Protected Overrides Sub Finalize()
    '     Dispose(disposing:=False)
    '     MyBase.Finalize()
    ' End Sub
End Class

24.4 Memory Leak Sources

Event handlers that are never removed (RemoveHandler), static (Shared) collections holding objects, undisposed resources, timers, and caches without eviction.