IDisposable and using

IDisposable

A type that holds something outside managed memory (a file handle, a socket, a lock, a database connection) implements IDisposable: one method, Dispose, that releases it. The garbage collector frees the memory of the object but knows nothing about the handle, so the program has to call Dispose itself.

using (var first = new Resource("first")) { first.Use(); } Console.WriteLine("after block"); var second = new Resource("second"); second.Use(); second.Dispose(); Console.WriteLine("done"); class Resource(string name) : IDisposable { public void Use() => Console.WriteLine($"using {name}"); public void Dispose() => Console.WriteLine($"dispose {name}"); }

dotnet run

using first
dispose first
after block
using second
dispose second
done

The two forms did the same thing. The block called Dispose at the closing brace, and the second object was disposed by hand. The difference appears when the code throws or returns early: the block and the declaration dispose on the way out, and a hand-written call does not run.

using block and using declaration

Dispose when an exception leaves

The cleanup belongs to the frame that opened the resource, so an exception in the middle of the block still disposes before the catch sees it:

try { using var resource = new Resource("inside"); resource.Use(); throw new InvalidOperationException("fail"); } catch (Exception e) { Console.WriteLine($"caught {e.Message}"); } Console.WriteLine("done"); class Resource(string name) : IDisposable { public void Use() => Console.WriteLine($"using {name}"); public void Dispose() => Console.WriteLine($"dispose {name}"); }

dotnet run

using inside
dispose inside
caught fail
done

dispose inside printed before caught fail, which is the finally of the using running while the exception left the block. A handle released after the catch would already have been reported as leaked; this order is the guarantee the statement gives.

Two resources, reverse order

Several resources in one scope are disposed in the reverse order of their creation, which is the order that respects dependencies between them:

using var outer = new Resource("outer"); using var inner = new Resource("inner"); outer.Use(); inner.Use(); Console.WriteLine("done"); class Resource(string name) : IDisposable { public void Use() => Console.WriteLine($"using {name}"); public void Dispose() => Console.WriteLine($"dispose {name}"); }

dotnet run

using outer
using inner
done
dispose inner
dispose outer

Inner closes first because it was opened second and may depend on the outer one: a transaction before its connection, a writer before its stream. The same rule holds for a block inside a block, and for the await using of the next lesson.

Exercises

  1. Throw inside the using block of the first program without a catch and check that dispose first still prints before the runtime text.
  2. Make Dispose idempotent with a flag, call it twice and explain why the second call must not throw.
  3. Put a return inside a using block and confirm the disposal order.
  4. Implement IDisposable explicitly and try to call Dispose on the object without a cast.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does IDisposable promise?

    Answer

    A Dispose method that releases unmanaged resources

    The GC frees memory; Dispose is the class own release of everything else.

  2. When does a using declaration dispose its object?

    Answer

    At the end of the enclosing scope

    The variable lives to the end of the method body, and the disposal is placed at that exit.

  3. What does this program print? using (var r = new R("a")) { Console.WriteLine(r.N); } class R(string n) : IDisposable { public string N => n; public void Dispose() => Console.WriteLine("bye " + n); }

    Answer

    a and then bye a

    The body runs first and the block disposes at its closing brace.

  4. How many times does Dispose run for a using block that throws?

    Answer

    Once, on the way out

    The using compiles to try/finally, and the finally runs once.

  5. In which order are two using declarations disposed?

    Answer

    Reverse order of declaration

    The nested scopes close from the inside out, so the last opened closes first.

  6. What does this program print? var a = new R("1"); var b = new R("2"); a.Dispose(); Console.WriteLine("x"); class R(string n) : IDisposable { public void Dispose() => Console.WriteLine("d" + n); }

    Answer

    d1 and then x

    Only the explicit call disposes, and it happens before the print.

  7. Why is a hand-written Dispose call dangerous?

    Answer

    It does not run when the block throws or returns early

    Only the using statement guarantees the call on every exit path.

  8. What does a using statement compile to?

    Answer

    A try/finally with a null check and a Dispose call

    The finally block is what releases the resource on any path.

  9. Which type must a class implement to work in a using statement?

    Answer

    IDisposable, or have a public Dispose method in the pattern

    The compiler accepts the interface or the Dispose pattern, and the interface is the clear form.

  10. What happens to the file handle of a FileStream that is never disposed?

    Answer

    It stays open until the process ends or a finalizer releases it

    The GC frees the object later and a finalizer may close it, but the handle lives until then.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev