Back to results for “Generics”
C# › Generics

How would you implement a generic, reusable object pool using generic constraints to ensure poolable objects can be properly reset?

Advanced

Answer

Constrain the pool's type parameter to an interface (like IPoolable) requiring a Reset() method, letting the generic pool safely call it when returning an object to the pool — this avoids unsafe casting or reflection while keeping the pool fully generic and reusable across any poolable type.
public interface IPoolable { void Reset(); }

public class ObjectPool<T> where T : class, IPoolable, new() {
  private readonly Stack<T> _pool = new();
  public T Rent() => _pool.Count > 0 ? _pool.Pop() : new T();
  public void Return(T item) { item.Reset(); _pool.Push(item); }
}
Real-world example Building a reusable pool for expensive-to-create objects (like StringBuilder or a game entity) to reduce garbage collection pressure in a hot loop.

Common follow-ups: How does this hand-rolled pool compare to the built-in Microsoft.Extensions.ObjectPool library's ObjectPool<T>?