CKTIS / C#
Resource disposal
Resource disposal is controlled cleanup when a resource is no longer needed. Synchronous `using` can call `IDisposable.Dispose` or a `Dispose` method that matches the disposal pattern on a `ref struct`, even if the type does not implement `IDisposable`. For asynchronous cleanup through `IAsyncDisposable.DisposeAsync`, use `await using`. Both constructs arrange cleanup when control leaves the scope, including because of an exception. Disposal is distinct from garbage collection reclaiming memory.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
using (Resource resource = new Resource()) { /* use resource */ }
using Resource resource = new Resource();
await using AsyncResource resource = new AsyncResource();Resource disposal is controlled cleanup, such as closing a file or releasing a handle. IDisposable.Dispose is a parameterless method returning void that performs this cleanup. The GC reclaims managed memory but does not automatically call Dispose. An ordinary variable going out of scope does not itself dispose its resource.
A using (...) { ... } statement disposes its resource when its block is exited. A using var resource = ...; declaration does so when its enclosing scope is exited. The compiler provides try/finally semantics: this also covers return and exception propagation. Multiple resources are disposed in reverse declaration order; a null value is skipped.
Dispose resources whose lifetime you own; do not dispose an object merely because you received a reference to it. After disposal, do not use the resource unless its documentation explicitly permits this. A Dispose implementation should tolerate repeated calls. A finalizer is a separate mechanism with nondeterministic timing, not a replacement for using.
For asynchronous cleanup through IAsyncDisposable.DisposeAsync, use await using; ordinary using does not await asynchronous cleanup. The example uses synchronous IDisposable: DemoResource only simulates cleanup with a message. Disposed appears before Caught because cleanup occurs while leaving the try scope.
Examples
using System;
try
{
using var resource = new DemoResource();
Console.WriteLine("Working");
throw new InvalidOperationException("Demo");
}
catch (InvalidOperationException)
{
Console.WriteLine("Caught");
}
sealed class DemoResource : IDisposable
{
private bool disposed;
public void Dispose()
{
if (disposed)
return;
disposed = true;
Console.WriteLine("Disposed");
}
}
Result
Working Disposed Caught
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.