CKTIS / C#
System.Func<T> and Action<T>: factory and reset in an object pool
Use `Func<T>` as a parameterless factory and `Action<T>` to reset a returned object in your own pool.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
// System delegate declarations (.NET 8)
public delegate TResult Func<out TResult>();
public delegate void Action<in T>(T obj);
// In a custom ObjectPool<T> where T : class, with using System;
// Constructor signature: public ObjectPool(Func<T> factory, Action<T> reset)
T item = factory();
reset(item);The lesson label System.Func<T> i Action<T> pairs two delegate types from the System namespace in C# 12 and .NET 8. In Func<T>, T is the result type: factory() takes no arguments and returns a T. In Action<T>, T is the parameter type: reset(item) takes one argument by value and returns void. For a class, the reference is copied, so the reset can still mutate the same object.
Do not confuse these with Func<T, TResult> (one input and a result) or nongeneric Action (no input and no result). Pass a compatible named method or lambda to the constructor and invoke it later. For reference types, out lets you assign Func<Derived> to Func<Base>, and in lets you assign Action<Base> to Action<Derived>; these markers describe variance, not by-reference invocation.
In the custom ObjectPool<T> below, Rent() calls the factory only when no object is available. Return(item) runs the reset before it may retain the object, even if the single slot is already full. Action<T> does not return an acceptance decision; if reset throws, the exception propagates to the caller and that call does not store the object.
After returning an object, do not use it or return it again. The example is not thread-safe and does not manage disposal. This is a custom type, not Microsoft.Extensions.ObjectPool.ObjectPool<T>; that library provides PooledObjectPolicy<T> to customize creation and return handling.
Examples
using System;
using System.Collections.Generic;
var pool = new ObjectPool<List<string>>(
static () => new List<string>(),
static list => list.Clear());
var first = pool.Rent();
first.Add("temporary");
pool.Return(first);
var second = pool.Rent();
Console.WriteLine($"Same instance: {object.ReferenceEquals(first, second)}");
Console.WriteLine($"Item count: {second.Count}");
pool.Return(second);
sealed class ObjectPool<T> where T : class
{
private readonly Func<T> _factory;
private readonly Action<T> _reset;
private T? _available;
public ObjectPool(Func<T> factory, Action<T> reset)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_reset = reset ?? throw new ArgumentNullException(nameof(reset));
}
public T Rent()
{
if (_available is T item)
{
_available = null;
return item;
}
return _factory() ?? throw new InvalidOperationException("The factory returned null.");
}
public void Return(T item)
{
ArgumentNullException.ThrowIfNull(item);
_reset(item);
_available ??= item;
}
}Result
Same instance: True Item count: 0
The factory creates a list on the first rent. `Clear()` removes its item on return, and the second rent gets the same list, now empty.
Related lessons
- C# · Lesson 13 · Advanced · Version: 3