Dispose and Finalize in C#: IDisposable, Finalizers and SafeHandle (.NET 10)

Leave a file handle open in a busy service and it stays open until the garbage collector notices. C# gives you two cleanup tools, Dispose and Finalize, and they behave very differently.

Quick answer: In C#, Dispose() from IDisposable releases a resource the moment you call it, usually through a using statement. Finalize is the ~ClassName() finalizer the garbage collector runs later, at a time you can’t control, as a safety net.

using var export = new OrderExport("Jenna Morales");   // Dispose() runs at the end of the scope

In this tutorial, I’ll walk you through dispose and finalize in C# the way my team uses them on .NET 10: IDisposable, using, finalizers, the Dispose(bool) pattern, SafeHandle and IAsyncDisposable, each run for real.

What You Need Before You Start with Dispose and Finalize

  • The .NET 10 SDK. Every example is a single file you run with dotnet run File.cs.
  • VS Code with the C# Dev Kit, or any editor. File-based apps are new in .NET 10; see what is new in .NET 10.
  • The sample: a Portland outdoor store exporting orders for Jenna Morales, Tyler Brooks and Dana Price.

Step 1: Implement IDisposable and Call Dispose with using

IDisposable has one method, Dispose(). Implementing it works like any other interface in C#; the using statement then calls it for you when the block ends:

using (var jenna = new OrderExport("Jenna Morales"))
    Console.WriteLine("  writing Jenna's order");

Console.WriteLine("-- using declaration --");
Ship();
Console.WriteLine("Done");

static void Ship()
{
    using var tyler = new OrderExport("Tyler Brooks");
    using var dana = new OrderExport("Dana Price");
    Console.WriteLine("  writing two orders");
}

class OrderExport : IDisposable
{
    readonly string _name;
    public OrderExport(string name) { _name = name; Console.WriteLine($"Open {name}"); }
    public void Dispose() => Console.WriteLine($"Dispose {_name}");
}

Output:

Open Jenna Morales
  writing Jenna's order
Dispose Jenna Morales
-- using declaration --
Open Tyler Brooks
Open Dana Price
  writing two orders
Dispose Dana Price
Dispose Tyler Brooks
Done
C# OrderExport class implementing IDisposable, called with a using statement and two using declarations, with the open and dispose order printed in the VS Code terminal
using calls Dispose at the end of the block; using declarations dispose in reverse order

Jenna’s export is disposed right after its block. Tyler and Dana go when Ship() returns, Dana first: reverse order.

using Statement vs using Declaration

The C# 8 using declaration (using var x = ...;) drops the braces and disposes at the end of the enclosing scope.

Both forms compile to a try/finally, so Dispose() runs even when the block throws, just like the finally block in try-catch in C#.

Step 2: Add a Finalizer (~ClassName) and See When the GC Runs It

A finalizer is a method named after the class with a tilde. It takes no parameters or modifiers, a class can have only one, and you can never call it yourself. Here we force a collection, purely to make the timing visible:

using System.Runtime.CompilerServices;

MakeReport("Q3 sales");
Console.WriteLine("Report dropped, no finalizer yet");
GC.Collect();                    // demo only
GC.WaitForPendingFinalizers();   // demo only
Console.WriteLine("After GC.Collect");

MakeReport("Q4 sales");
Console.WriteLine("Program ends");

[MethodImpl(MethodImplOptions.NoInlining)]
static void MakeReport(string name) => new TempReport(name);

class TempReport(string name)
{
    ~TempReport() => Console.WriteLine($"Finalizer ran for {name}");
}

Output:

Report dropped, no finalizer yet
Finalizer ran for Q3 sales
After GC.Collect
Program ends
C# finalizer ~TempReport running only after GC.Collect and GC.WaitForPendingFinalizers, while the second report is never finalized before the .NET 10 program exits
The Q3 finalizer runs only when we force a collection; Q4’s never runs

The Q3 report’s finalizer ran only after GC.Collect(). The Q4 report was also unreachable, yet its finalizer never printed, because .NET 5 and later (including .NET 10) don’t run finalizers when the process exits.

Important: GC.Collect() and GC.WaitForPendingFinalizers() are here only for the demo. In your real code, they hurt performance and don’t turn finalizers into a cleanup plan.

Finalizers only work on classes; a structure in C# can’t declare one.

Why You Can’t Override Finalize Directly (CS0249)

The compiler turns ~TempReport() into a Finalize() override that calls base.Finalize() in a finally block. Writing that override yourself is a build error:

Console.WriteLine("Build check");

class TempReport
{
    protected override void Finalize() { }
}

Build output:

C:\DotNetDemo\DisposeFinalizeDemo\OverrideFinalize.cs(5,29): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
C:\DotNetDemo\DisposeFinalizeDemo\OverrideFinalize.cs(5,29): error CS0249: Do not override object.Finalize. Instead, provide a destructor.

The build failed. Fix the build errors and run again.
C# error CS0249 Do not override object.Finalize. Instead, provide a destructor, shown in the VS Code terminal for a protected override void Finalize method
CS0249: C# wants the ~ClassName() syntax, not an override

Step 3: Combine Dispose and Finalize with the Dispose(bool) Pattern

When a class owns unmanaged memory directly, we use both: Dispose() for the normal path and a finalizer as the backup. Both call one protected virtual Dispose(bool disposing) method:

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

var tyler = new PriceCache("Tyler Brooks");
tyler.Dispose();
tyler.Dispose();                 // second call does nothing

Forget("Jenna Morales");
GC.Collect();                    // demo only
GC.WaitForPendingFinalizers();

[MethodImpl(MethodImplOptions.NoInlining)]
static void Forget(string owner) => new PriceCache(owner);

class PriceCache(string owner) : IDisposable
{
    IntPtr _buffer = Marshal.AllocHGlobal(1024);   // unmanaged memory
    bool _disposed;

    ~PriceCache() => Dispose(false);

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed) return;
        Console.WriteLine($"{owner}: Dispose({disposing})");
        Marshal.FreeHGlobal(_buffer);
        _disposed = true;
    }
}

Output:

Tyler Brooks: Dispose(True)
Jenna Morales: Dispose(False)

Tyler’s cache printed Dispose(True) once, even though we called Dispose() twice; the _disposed flag makes it safe to repeat. Jenna’s was never disposed, so the finalizer cleaned up with Dispose(False).

GC.SuppressFinalize(this) is why Tyler’s finalizer never ran: it tells the GC the cleanup is already done. When disposing is false, touch only unmanaged resources, because managed objects may already be finalized.

Keep Dispose(bool) protected virtual so subclasses can extend it; that’s plain method overriding in C#, as Step 4 shows.

Step 4: Dispose a Derived Class (IDisposable with Inheritance)

A derived class doesn’t implement IDisposable again. It overrides Dispose(bool), cleans up its own fields and calls base.Dispose(disposing), the usual inheritance in C# hook:

var export = new CsvExport();
export.Dispose();

try { export.Write("Order 3107"); }
catch (ObjectDisposedException ex) { Console.WriteLine(ex.Message); }

class StoreResource : IDisposable
{
    protected bool Disposed { get; private set; }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (Disposed) return;
        if (disposing) Console.WriteLine("Base: released connection");
        Disposed = true;
    }
}

class CsvExport : StoreResource
{
    readonly StringWriter _writer = new();

    public void Write(string line)
    {
        ObjectDisposedException.ThrowIf(Disposed, this);
        _writer.WriteLine(line);
    }

    protected override void Dispose(bool disposing)
    {
        if (!Disposed && disposing)
        {
            _writer.Dispose();
            Console.WriteLine("Derived: closed CSV writer");
        }
        base.Dispose(disposing);
    }
}

Output:

Derived: closed CSV writer
Base: released connection
Cannot access a disposed object.
Object name: 'CsvExport'.

The derived class closed its CSV writer first, then the base released its connection. Calling Write afterwards threw ObjectDisposedException, thanks to the .NET 7+ ObjectDisposedException.ThrowIf helper.

Step 5: Use SafeHandle Instead of Writing a Finalizer

Microsoft’s advice is to avoid finalizers and wrap native handles in SafeHandle. It’s an abstract class that already has a finalizer and releases the handle exactly once:

using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

var cache = new PriceCache();
Console.WriteLine($"Handle valid: {!cache.Handle.IsInvalid}");
cache.Dispose();
cache.Dispose();
Console.WriteLine($"Handle closed: {cache.Handle.IsClosed}");

sealed class PriceCache : IDisposable
{
    public BufferHandle Handle { get; } = BufferHandle.Allocate(1024);
    public void Dispose() => Handle.Dispose();
}

sealed class BufferHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    BufferHandle() : base(ownsHandle: true) { }

    public static BufferHandle Allocate(int bytes)
    {
        var h = new BufferHandle();
        h.SetHandle(Marshal.AllocHGlobal(bytes));
        return h;
    }

    protected override bool ReleaseHandle()   // SafeHandle's own finalizer calls this too
    {
        Marshal.FreeHGlobal(handle);
        Console.WriteLine("ReleaseHandle: freed 1024 bytes");
        return true;
    }
}

Output:

Handle valid: True
ReleaseHandle: freed 1024 bytes
Handle closed: True

We called Dispose() twice and ReleaseHandle ran once, with no finalizer or flag in PriceCache. You’ll rarely write one yourself: FileStream and friends already use SafeFileHandle.

Step 6: Dispose Asynchronously with IAsyncDisposable and await using

When cleanup involves I/O, such as flushing a buffer to a server, implement IAsyncDisposable. DisposeAsync() returns a ValueTask, and await using awaits it:

await using (var jenna = new AuditLog("Jenna Morales"))
{
    await jenna.WriteAsync("order 3107 refunded");
}

await using var tyler = new AuditLog("Tyler Brooks");
await tyler.WriteAsync("order 3108 shipped");
Console.WriteLine("End of Main");

sealed class AuditLog(string user) : IAsyncDisposable
{
    readonly StringWriter _buffer = new();
    public Task WriteAsync(string text) => _buffer.WriteAsync($"{user}: {text}");
    public async ValueTask DisposeAsync()
    {
        await Task.Delay(50);            // e.g. flush to a server
        Console.WriteLine($"Flushed -> {_buffer}");
        await _buffer.DisposeAsync();
    }
}

Output:

Flushed -> Jenna Morales: order 3107 refunded
End of Main
Flushed -> Tyler Brooks: order 3108 shipped
C# AuditLog class implementing IAsyncDisposable with DisposeAsync, used with an await using block and an await using declaration in a .NET 10 file-based app
await using flushes Jenna’s log after its block and Tyler’s at the end of the program

Jenna’s log flushed when its block ended; Tyler’s flushed after End of Main, at the end of the top-level code. If a class can be disposed either way, implement both interfaces so a plain Dispose() call doesn’t leak.

Dispose vs Finalize in C#: Cheat Sheet

This is the table we keep pinned for code reviews, built from the runs above. It also answers one of the classic C# interview questions for experienced developers:

Dispose()Finalize (~ClassName)
Declared byIDisposable interfaceFinalizer syntax, compiled to Object.Finalize
Called byYour code or usingThe garbage collector’s finalizer thread
TimingDeterministic, right awayNondeterministic, maybe never
Cleans upManaged and unmanaged resourcesUnmanaged resources only
CostCheapObject survives an extra GC cycle
Allowed onClasses and structsClasses only
Use itAlways, for anything disposableRarely; prefer SafeHandle

Does .NET Run Finalizers When the Program Exits?

No. .NET Framework tried to run pending finalizers at shutdown, but .NET 5 and later, including .NET 10, don’t. Step 2’s Q4 report proves it.

If you need cleanup at exit, dispose explicitly or dispose inside an AppDomain.CurrentDomain.ProcessExit handler, subscribed like any of the events in C#.

Common Mistakes to Avoid with Dispose and Finalize

MistakeWhat happensFix
Forgetting usingHandle stays open until a GC, or exitusing / await using
Empty finalizerEvery instance goes through the finalization queueDelete it
Touching managed fields in Dispose(false)They may already be finalizedFree unmanaged state only
No GC.SuppressFinalizeFinalizer runs after Dispose anywayCall it in Dispose()
protected override void Finalize()CS0249Use ~ClassName()

Next Steps

Pick the lightest tool that works: using for everyday types, the Dispose(bool) pattern for base classes, SafeHandle for native handles. Then see how cleanup fits constructors in C#, where resources are usually acquired.

A few more C# class topics worth a look:

Frequently Asked Questions

What is the difference between Dispose and Finalize in C#?

Dispose() is called by your code or a using statement and releases resources immediately. Finalize is the ~ClassName() finalizer the garbage collector runs later, at an unpredictable time, as a backup.

Should I call GC.Collect to make finalizers run?

No. Use it only in demos or tests. In production it costs performance, and finalizers still aren’t a reliable cleanup path.

Does every class with IDisposable need a finalizer?

No. A finalizer is needed only when the class holds an unmanaged resource directly, and SafeHandle usually removes even that need. See Implement a Dispose method on Microsoft Learn.

Is it safe to call Dispose twice?

It should be. Microsoft’s guidance says Dispose must be idempotent, so later calls do nothing and never throw.

Can a struct have a finalizer?

No. Finalizers are only allowed in classes, as the Finalizers page on Microsoft Learn notes. A struct can still implement IDisposable.