Codectionary / Developer documentation / C#

ArrayPool Buffer Ownership

ArrayPool<T> lends reusable arrays to reduce repeated allocations. Rent returns at least the requested length, possibly with old contents; the caller must initialize the portion it reads and return the array to the same pool exactly once. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

ArrayPool<T> lends reusable arrays to reduce repeated allocations. Rent returns at least the requested length, possibly with old contents; the caller must initialize the portion it reads and return the array to the same pool exactly once. Use a .NET 8+ console project; replace Program.cs with this C# example.

Only the three initialized elements are processed, even if the rented array is larger. The finally block returns ownership on both normal and exceptional exits; neither the array nor any view into it may be used afterward.

Syntax

T[] buffer = pool.Rent(length); try { /* use buffer */ } finally { pool.Return(buffer, clearArray: true); }

Examples

ArrayPool Buffer Ownership

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
using System.Buffers;
var pool = ArrayPool<int>.Shared;
const int length = 3;
int[] buffer = pool.Rent(length);
try
{
    for (int i = 0; i < length; i++) buffer[i] = (i + 1) * 10;
    int total = 0;
    for (int i = 0; i < length; i++) total += buffer[i];
    Console.WriteLine(total);
}
finally
{
    pool.Return(buffer, clearArray: true);
}
  1. Expected output: 60
  2. Only the three initialized elements are processed, even if the rented array is larger. The finally block returns ownership on both normal and exceptional exits; neither the array nor any view into it may be used afterward.
  3. Return each rented array exactly once to the same pool, and never retain a usable alias after returning it.

Best practices

  • Return each rented array exactly once to the same pool, and never retain a usable alias after returning it.
  • clearArray: true clears contents if the pool retains the buffer for reuse; it is not guaranteed to erase a discarded array. Explicitly clear sensitive data before returning when erasure is required.

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

Specifications & further reading