Read the syntax
Implement deterministic cleanup for a small sealed owner and distinguish disposal from garbage collection.
Leaving the block calls Dispose before the following statement.
What it is and why to use it
Some resources need a clear end to their useful lifetime rather than waiting for garbage collection. IDisposable supplies a Dispose method that callers can invoke directly or through using. It can release owned disposable objects or another logical resource. Garbage collection reclaims managed memory; it does not automatically call Dispose on every unreachable object.
How it works
A simple sealed type can implement Dispose directly. Make repeated disposal safe and reject operations after disposal when appropriate. More complex inheritance or unmanaged resource ownership requires the documented dispose pattern and usually SafeHandle for native handles. These teaching types simulate a lifetime and own no native handles, so adding a finalizer would be unnecessary.
Common mistakes and limitations
Do not dispose an object that another component still owns. Do not assume using prevents every exception or that Dispose cannot throw. Idempotence is not the same as thread safety. Keep cleanup small and avoid finalizers when there is no unmanaged resource requiring one.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
sealed class Lease : IDisposable { public void Dispose() { /* release owned resource */ } }Examples
Observe deterministic cleanup at a scope boundary
Use a simulated lease so the cleanup order is visible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using (var lease = new Lease()) {
Console.WriteLine("Working");
}
Console.WriteLine("After scope");
sealed class Lease : IDisposable {
public void Dispose() => Console.WriteLine("Released");
}
- The using statement owns the lease for its block.
- Leaving the block calls Dispose before the following statement.
- The printed order demonstrates deterministic cleanup. A real owner would release its actual owned resource in Dispose.
- Expected output: Working Released After scope
- Make resource ownership and scope explicit.
Make repeated cleanup safe and guard later use
Keep a simple disposed flag in a sealed teaching type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var lease = new Lease();
lease.Dispose();
lease.Dispose();
try { lease.Read(); }
catch (ObjectDisposedException) { Console.WriteLine("Already disposed"); }
sealed class Lease : IDisposable {
private bool disposed;
public void Read() => ObjectDisposedException.ThrowIf(disposed, this);
public void Dispose() {
if (disposed) return;
disposed = true;
Console.WriteLine("Released once");
}
}
- The first Dispose changes the lifetime state and performs cleanup.
- The second call returns without repeating that work.
- Read uses a runtime guard to reject later operations. This basic flag is not a concurrent ownership protocol.
- Expected output: Released once Already disposed
- Make resource ownership and scope explicit.
Best practices
- Make resource ownership and scope explicit.
- Choose a simple sealed implementation when inheritance and native handles are unnecessary.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference