using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
public class User : IFreeable {
public string Name {get;set;}
public int Age {get;set;}
public string Email {get;set;}
public bool Freed {get;set;}
public static void Main()
var allocator = new Allocator<User>(5);
var user = allocator.Alloc();
user.Email = "ben1@buildstarted.com";
var user2 = allocator.Alloc();
user2.Email = "ben2@buildstarted.com";
var user3 = allocator.Alloc();
user3.Email = "ben3@buildstarted.com";
var user4 = allocator.Alloc();
user4.Email = "ben4@buildstarted.com";
var user5 = allocator.Alloc();
user5.Email = "ben5@buildstarted.com";
var user6 = allocator.Alloc();
Console.WriteLine("Unable to allocate 6 users");
var user7 = allocator.Alloc();
public interface IFreeable {
public class Allocator<T> where T: IFreeable, new() {
public Allocator(int capacity, bool preallocate)
_managed = new T[capacity];
for (int i = 0; i != capacity; ++i)
result = _managed[--_freeEnd];
Debug.Assert(!obj.Freed);
if (_freeEnd < _managed.Length)
_managed[_freeEnd++] = obj;
throw new Exception("Can't store more than " + _managed.Length + " free objects");