Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.IDisposable: ownership and deterministic cleanup

`System.IDisposable` is the synchronous cleanup contract. Use `using` to choose when cleanup runs, and make it clear who is responsible for it.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

// Separate syntax fragments, not a complete program.
// .NET API excerpt for reference only; do not redeclare it in consumer code.
namespace System
{
    public interface IDisposable
    {
        void Dispose();
    }
}

// In the two alternatives below, Acquire() is a placeholder for resource acquisition.

// Statement: dispose on exit from the block.
using (System.IDisposable resource = Acquire())
{
    // Use resource.
}

// Declaration (alternative): dispose on exit from the enclosing scope.
using System.IDisposable resource = Acquire();

System.IDisposable is a .NET interface with one method, void Dispose(), which takes no arguments and returns no value. It can release an unmanaged resource, dispose an owned object, or return a managed array to a pool. Disposing an object does not free the object's own memory or replace garbage collection (GC).

A using (...) { ... } statement calls Dispose() when control leaves the block; a using var resource = ...; declaration does so when control leaves the scope where it was declared. After successful acquisition of a non-null resource, the compiler arranges the call through try/finally, including on return or an exception in the body. using does not catch exceptions. For asynchronous cleanup, use await using with System.IAsyncDisposable.

The owner is responsible for cleanup; code that only borrows a resource should not dispose it. Here, IBufferLease inherits IDisposable, and ResourceScope implements IDisposable itself, takes ownership of the lease, and forwards disposal to it. BufferLease returns the array exactly once to the same pool and rejects later access with ObjectDisposedException. Repeated calls to Dispose() do nothing (idempotence); this does not imply thread safety.

Rent(1) guarantees at least one element, but it does not guarantee a zero-initialized array. Write before reading, and do not use any retained reference to the array after returning it. clearArray: true clears the array if the pool keeps it for reuse; it is not a secure-erasure guarantee.

Examples

#nullable enable
using System;
using System.Buffers;

IBufferLease lease = new BufferLease();
IDisposable scope = new ResourceScope(lease);

using (scope)
{
    lease.Value = 42;
    Console.WriteLine(lease.Value);
}

scope.Dispose();

try
{
    _ = lease.Value;
}
catch (ObjectDisposedException)
{
    Console.WriteLine("Lease disposed.");
}

interface IBufferLease : IDisposable
{
    int Value { get; set; }
}

sealed class BufferLease : IBufferLease
{
    private readonly ArrayPool<int> _pool = ArrayPool<int>.Shared;
    private int[]? _buffer;

    public BufferLease() => _buffer = _pool.Rent(1);

    private int[] Buffer =>
        _buffer ?? throw new ObjectDisposedException(nameof(BufferLease));

    public int Value
    {
        get => Buffer[0];
        set => Buffer[0] = value;
    }

    public void Dispose()
    {
        int[]? buffer = _buffer;
        if (buffer is null)
            return;

        _buffer = null;
        _pool.Return(buffer, clearArray: true);
    }
}

sealed class ResourceScope : IDisposable
{
    private IBufferLease? _lease;

    public ResourceScope(IBufferLease lease) =>
        _lease = lease ?? throw new ArgumentNullException(nameof(lease));

    public void Dispose()
    {
        IBufferLease? lease = _lease;
        _lease = null;
        lease?.Dispose();
    }
}

Result

42
Lease disposed.

With C# 12 and .NET 8, the program prints `42` and then `Lease disposed.`. Exiting `using` returns the array; the second call to `scope.Dispose()` does nothing. The caught `ObjectDisposedException` shows that the lease rejects a later read, not that the pool reused the array.

Related lessons

  • C# · Lesson 31 · Advanced · Version: 3
  • C# · Lesson 32 · Advanced · Version: 3

Sources