Disposable resources and using
Disposable resources and using
Some objects own resources that need explicit cleanup, such as a file handle or a connection. IDisposable exposes a Dispose() method. The C# using statement or declaration arranges disposal when execution leaves the relevant scope. This is separate from garbage collection, which manages memory and does not guarantee timely release of external resources.
using System;using (LabHandle handle = new LabHandle()){ Console.WriteLine("Work");}Console.WriteLine("After block");sealed class LabHandle : IDisposable{ public LabHandle() => Console.WriteLine("Acquire"); public void Dispose() => Console.WriteLine("Dispose");}The synthetic handle records acquisition and cleanup. It does not own real external resources. The block ends before After block is printed.
Expected output (reasoned, not executed):
AcquireWorkDisposeAfter blockScope controls lifetime
Use using (Resource r = new Resource()) { ... } for a block-scoped lifetime. A declaration using Resource r = new Resource(); keeps the resource until the end of the enclosing scope. Both arrange cleanup after successful acquisition even if execution leaves by return or exception. Multiple using variables are disposed in reverse declaration order. The using variable cannot be reassigned. This lesson covers ordinary synchronous IDisposable; asynchronous disposal is covered later.
Ownership is a design responsibility
Dispose a resource your code owns when it is finished with it. A caller-owned object passed to a method is not automatically transferred to that method. Read the API ownership contract. Do not continue using a disposed resource unless its contract explicitly permits that operation. Dispose can itself fail; using is not a guarantee of successful cleanup or crash recovery. When a constructor fails before returning an object, the caller cannot dispose that unreturned instance; the constructor must manage resources it has already acquired.
using System;Console.WriteLine(ReadCount());static int ReadCount(){ using LabHandle handle = new LabHandle(); Console.WriteLine("Read"); return 3;}sealed class LabHandle : IDisposable{ public void Dispose() => Console.WriteLine("Dispose");}The return value is evaluated, cleanup runs on scope exit, then the caller prints the returned integer.
Expected output (reasoned, not executed):
ReadDispose3using System;try{ using LabHandle first = new LabHandle("First"); using LabHandle second = new LabHandle("Second"); throw new InvalidOperationException();}catch (InvalidOperationException){ Console.WriteLine("Handled");}sealed class LabHandle : IDisposable{ private readonly string _name; public LabHandle(string name) => _name = name; public void Dispose() => Console.WriteLine("Dispose " + _name);}The using declarations are nested lifetime boundaries in effect. The later resource is disposed first, then the earlier one; the outer catch runs afterward.
Expected output (reasoned, not executed):
Dispose SecondDispose FirstHandledCommon mistakes
Do not assume using immediately disposes an object after its last apparent use. A using declaration disposes at scope exit, which can be much later. Use a smaller block when a resource must be released sooner. Do not confuse using System; (a namespace import) with the resource-management statement.
Practice
Modify the two-handle example to use a nested using block for Second, then print Between inside the outer First scope. Print End after the outer scope. Run the normal path without throwing and predict the order.
Predict the outcome before checking your work. The separate manual practice and quiz are staged, not automatically graded.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Disposable resources and using — knowledge check
Apply the lesson concepts to the following scenarios.
When does a using declaration normally dispose its resource?
Which method is called for a normal IDisposable class by using?
Two resources are acquired in order First, Second. What is their normal disposal order?
Should a method always dispose a caller-owned resource it receives?
Does using ensure cleanup succeeds if Dispose throws?