<p>I have a Queue&lt;T&gt; object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items.  Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class?</p>

[{'answer_id': 1297, 'author': 'CodingWithoutComments', 'author_id': 25, 'author_profile': 'https://Stackoverflow.com/users/25', 'pm_score': 2, 'selected': False, 'text': "<p>Why wouldn't you just use an array with a size of 2?  A Queue is supposed to be able to dynamically grow and shrink.</p>\n\n<p>Or create a wrapper class around an instance of <code>Queue&lt;T&gt;</code> instance and each time one enqueues a <code>&lt;T&gt;</code> object, check the size of the queue.  If larger than 2, dequeue the first item.</p>\n"}, {'answer_id': 1303, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 3, 'selected': False, 'text': "<p>You should create your own class, a ringbuffer would probably fit your needs.</p>\n\n<p>The data structures in .NET that allows you to specify capacity, except for array, uses this to build the internal data structure used to hold the internal data.</p>\n\n<p>For instance, for a list, capacity is used to size an internal array. When you start adding elements to the list, it'll start filling this array from index 0 and up, and when it reaches your capacity, it increases the capacity to a new higher capacity, and continues filling it up.</p>\n"}, {'answer_id': 1305, 'author': 'tags2k', 'author_id': 192, 'author_profile': 'https://Stackoverflow.com/users/192', 'pm_score': 6, 'selected': True, 'text': "<p>I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along.</p>\n\n<pre><code>public class LimitedQueue&lt;T&gt; : Queue&lt;T&gt;\n{\n    public int Limit { get; set; }\n\n    public LimitedQueue(int limit) : base(limit)\n    {\n        Limit = limit;\n    }\n\n    public new void Enqueue(T item)\n    {\n        while (Count &gt;= Limit)\n        {\n            Dequeue();\n        }\n        base.Enqueue(item);\n    }\n}\n</code></pre>\n"}, {'answer_id': 233606, 'author': 'Marcus Griep', 'author_id': 28645, 'author_profile': 'https://Stackoverflow.com/users/28645', 'pm_score': 4, 'selected': False, 'text': '<p>I would recommend that you pull up the <a href="http://www.itu.dk/research/c5" rel="noreferrer">C5 Library</a>.  Unlike SCG (System.Collections.Generic), C5 is programmed to interface and designed to be subclassed.  Most public methods are virtual and none of the classes are sealed.  This way, you won\'t have to use that icky "new" keyword which wouldn\'t trigger if your <code>LimitedQueue&lt;T&gt;</code> were cast to a <code>SCG.Queue&lt;T&gt;</code>.  With C5 and using close to the same code as you had before, you would derive from the <code>CircularQueue&lt;T&gt;</code>.  The <code>CircularQueue&lt;T&gt;</code> actually implements both a stack and a queue, so you can get both options with a limit nearly for free.  I\'ve rewritten it below with some 3.5 constructs:</p>\n\n<pre><code>using C5;\n\npublic class LimitedQueue&lt;T&gt; : CircularQueue&lt;T&gt;\n{\n    public int Limit { get; set; }\n\n    public LimitedQueue(int limit) : base(limit)\n    {\n        this.Limit = limit;\n    }\n\n    public override void Push(T item)\n    {\n        CheckLimit(false);\n        base.Push(item);\n    }\n\n    public override void Enqueue(T item)\n    {\n        CheckLimit(true);\n        base.Enqueue(item);\n    }\n\n    protected virtual void CheckLimit(bool enqueue)\n    {\n        while (this.Count &gt;= this.Limit)\n        {\n            if (enqueue)\n            {\n                this.Dequeue();\n            }\n            else\n            {\n                this.Pop();\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>I think that this code should do exactly what you were looking for.</p>\n'}, {'answer_id': 8136476, 'author': 'Robel.E', 'author_id': 1047575, 'author_profile': 'https://Stackoverflow.com/users/1047575', 'pm_score': 3, 'selected': False, 'text': '<p>Well I hope this class will helps You:<br>\nInternally the Circular FIFO Buffer use a Queue&lt;T&gt; with the specified size. \nOnce the size of the buffer is reached, it will replaces older items with new ones.</p>\n\n<p>NOTE: You can\'t remove items randomly. I set the method Remove(T item) to return false.\nif You want You can modify to remove items randomly</p>\n\n<pre><code>public class CircularFIFO&lt;T&gt; : ICollection&lt;T&gt; , IDisposable\n{\n    public Queue&lt;T&gt; CircularBuffer;\n\n    /// &lt;summary&gt;\n    /// The default initial capacity.\n    /// &lt;/summary&gt;\n    private int capacity = 32;\n\n    /// &lt;summary&gt;\n    /// Gets the actual capacity of the FIFO.\n    /// &lt;/summary&gt;\n    public int Capacity\n    {\n        get { return capacity; }          \n    }\n\n    /// &lt;summary&gt;\n    ///  Initialize a new instance of FIFO class that is empty and has the default initial capacity.\n    /// &lt;/summary&gt;\n    public CircularFIFO()\n    {            \n        CircularBuffer = new Queue&lt;T&gt;();\n    }\n\n    /// &lt;summary&gt;\n    /// Initialize a new instance of FIFO class that is empty and has the specified initial capacity.\n    /// &lt;/summary&gt;\n    /// &lt;param name="size"&gt; Initial capacity of the FIFO. &lt;/param&gt;\n    public CircularFIFO(int size)\n    {\n        capacity = size;\n        CircularBuffer = new Queue&lt;T&gt;(capacity);\n    }\n\n    /// &lt;summary&gt;\n    /// Adds an item to the end of the FIFO.\n    /// &lt;/summary&gt;\n    /// &lt;param name="item"&gt; The item to add to the end of the FIFO. &lt;/param&gt;\n    public void Add(T item)\n    {\n        if (this.Count &gt;= this.Capacity)\n            Remove();\n\n        CircularBuffer.Enqueue(item);\n    }\n\n    /// &lt;summary&gt;\n    /// Adds array of items to the end of the FIFO.\n    /// &lt;/summary&gt;\n    /// &lt;param name="item"&gt; The array of items to add to the end of the FIFO. &lt;/param&gt;\n     public void Add(T[] item)\n    { \n        int enqueuedSize = 0;\n        int remainEnqueueSize = this.Capacity - this.Count;\n\n        for (; (enqueuedSize &lt; item.Length &amp;&amp; enqueuedSize &lt; remainEnqueueSize); enqueuedSize++)\n            CircularBuffer.Enqueue(item[enqueuedSize]);\n\n        if ((item.Length - enqueuedSize) != 0)\n        {\n            Remove((item.Length - enqueuedSize));//remaining item size\n\n            for (; enqueuedSize &lt; item.Length; enqueuedSize++)\n                CircularBuffer.Enqueue(item[enqueuedSize]);\n        }           \n    }\n\n    /// &lt;summary&gt;\n    /// Removes and Returns an item from the FIFO.\n    /// &lt;/summary&gt;\n    /// &lt;returns&gt; Item removed. &lt;/returns&gt;\n    public T Remove()\n    {\n        T removedItem = CircularBuffer.Peek();\n        CircularBuffer.Dequeue();\n\n        return removedItem;\n    }\n\n    /// &lt;summary&gt;\n    /// Removes and Returns the array of items form the FIFO.\n    /// &lt;/summary&gt;\n    /// &lt;param name="size"&gt; The size of item to be removed from the FIFO. &lt;/param&gt;\n    /// &lt;returns&gt; Removed array of items &lt;/returns&gt;\n    public T[] Remove(int size)\n    {\n        if (size &gt; CircularBuffer.Count)\n            size = CircularBuffer.Count;\n\n        T[] removedItems = new T[size];\n\n        for (int i = 0; i &lt; size; i++)\n        {\n            removedItems[i] = CircularBuffer.Peek();\n            CircularBuffer.Dequeue();\n        }\n\n        return removedItems;\n    }\n\n    /// &lt;summary&gt;\n    /// Returns the item at the beginning of the FIFO with out removing it.\n    /// &lt;/summary&gt;\n    /// &lt;returns&gt; Item Peeked. &lt;/returns&gt;\n    public T Peek()\n    {\n        return CircularBuffer.Peek();\n    }\n\n    /// &lt;summary&gt;\n    /// Returns the array of item at the beginning of the FIFO with out removing it.\n    /// &lt;/summary&gt;\n    /// &lt;param name="size"&gt; The size of the array items. &lt;/param&gt;\n    /// &lt;returns&gt; Array of peeked items. &lt;/returns&gt;\n    public T[] Peek(int size)\n    {\n        T[] arrayItems = new T[CircularBuffer.Count];\n        CircularBuffer.CopyTo(arrayItems, 0);\n\n        if (size &gt; CircularBuffer.Count)\n            size = CircularBuffer.Count;\n\n        T[] peekedItems = new T[size];\n\n        Array.Copy(arrayItems, 0, peekedItems, 0, size);\n\n        return peekedItems;\n    }\n\n    /// &lt;summary&gt;\n    /// Gets the actual number of items presented in the FIFO.\n    /// &lt;/summary&gt;\n    public int Count\n    {\n        get\n        {\n            return CircularBuffer.Count;\n        }\n    }\n\n    /// &lt;summary&gt;\n    /// Removes all the contents of the FIFO.\n    /// &lt;/summary&gt;\n    public void Clear()\n    {\n        CircularBuffer.Clear();\n    }\n\n    /// &lt;summary&gt;\n    /// Resets and Initialize the instance of FIFO class that is empty and has the default initial capacity.\n    /// &lt;/summary&gt;\n    public void Reset()\n    {\n        Dispose();\n        CircularBuffer = new Queue&lt;T&gt;(capacity);\n    }\n\n    #region ICollection&lt;T&gt; Members\n\n    /// &lt;summary&gt;\n    /// Determines whether an element is in the FIFO.\n    /// &lt;/summary&gt;\n    /// &lt;param name="item"&gt; The item to locate in the FIFO. &lt;/param&gt;\n    /// &lt;returns&gt;&lt;/returns&gt;\n    public bool Contains(T item)\n    {\n        return CircularBuffer.Contains(item);\n    }\n\n    /// &lt;summary&gt;\n    /// Copies the FIFO elements to an existing one-dimensional array. \n    /// &lt;/summary&gt;\n    /// &lt;param name="array"&gt; The one-dimensional array that have at list a size of the FIFO &lt;/param&gt;\n    /// &lt;param name="arrayIndex"&gt;&lt;/param&gt;\n    public void CopyTo(T[] array, int arrayIndex)\n    {\n        if (array.Length &gt;= CircularBuffer.Count)\n            CircularBuffer.CopyTo(array, 0);           \n    }\n\n    public bool IsReadOnly\n    {\n        get { return false; }\n    }\n\n    public bool Remove(T item)\n    {\n        return false; \n    }\n\n    #endregion\n\n    #region IEnumerable&lt;T&gt; Members\n\n    public IEnumerator&lt;T&gt; GetEnumerator()\n    {\n       return CircularBuffer.GetEnumerator();\n    }\n\n    #endregion\n\n    #region IEnumerable Members\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        return CircularBuffer.GetEnumerator();\n    }\n\n    #endregion\n\n    #region IDisposable Members\n\n    /// &lt;summary&gt;\n    /// Releases all the resource used by the FIFO.\n    /// &lt;/summary&gt;\n    public void Dispose()\n    {          \n        CircularBuffer.Clear();\n        CircularBuffer = null;\n        GC.Collect();\n    }\n\n    #endregion\n}\n</code></pre>\n'}, {'answer_id': 8867737, 'author': 'mpen', 'author_id': 65387, 'author_profile': 'https://Stackoverflow.com/users/65387', 'pm_score': 2, 'selected': False, 'text': '<p>If it\'s of any use to anyone, I made a <code>LimitedStack&lt;T&gt;</code>.</p>\n\n<pre><code>public class LimitedStack&lt;T&gt;\n{\n    public readonly int Limit;\n    private readonly List&lt;T&gt; _stack;\n\n    public LimitedStack(int limit = 32)\n    {\n        Limit = limit;\n        _stack = new List&lt;T&gt;(limit);\n    }\n\n    public void Push(T item)\n    {\n        if (_stack.Count == Limit) _stack.RemoveAt(0);\n        _stack.Add(item);\n    }\n\n    public T Peek()\n    {\n        return _stack[_stack.Count - 1];\n    }\n\n    public void Pop()\n    {\n        _stack.RemoveAt(_stack.Count - 1);\n    }\n\n    public int Count\n    {\n        get { return _stack.Count; }\n    }\n}\n</code></pre>\n\n<p>It removes the oldest item (bottom of stack) when it gets too big.</p>\n\n<p>(This question was the top Google result for "C# limit stack size")</p>\n'}, {'answer_id': 50261664, 'author': 'SwiftArchitect', 'author_id': 218152, 'author_profile': 'https://Stackoverflow.com/users/218152', 'pm_score': 3, 'selected': False, 'text': '<h3>Concurrent Solution</h3>\n<pre><code>public class LimitedConcurrentQueue&lt;ELEMENT&gt; : ConcurrentQueue&lt;ELEMENT&gt;\n{\n    public readonly int Limit;\n\n    public LimitedConcurrentQueue(int limit)\n    {\n        Limit = limit;\n    }\n\n    public new void Enqueue(ELEMENT element)\n    {\n        base.Enqueue(element);\n        if (Count &gt; Limit)\n        {\n            TryDequeue(out ELEMENT discard);\n        }\n    }\n}\n</code></pre>\n<p>Note: Since <code>Enqueue</code> controls the addition of elements, and does so one at a time, there is no need to execute a <code>while</code> for <code>TryDequeue</code>.</p>\n'}, {'answer_id': 62108498, 'author': 'Brandon', 'author_id': 674237, 'author_profile': 'https://Stackoverflow.com/users/674237', 'pm_score': 1, 'selected': False, 'text': '<p>You can use a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=netcore-3.1" rel="nofollow noreferrer"><code>LinkedList&lt;T&gt;</code></a> and add thread safety:</p>\n\n<pre><code>public class Buffer&lt;T&gt; : LinkedList&lt;T&gt;\n{\n    private int capacity;\n\n    public Buffer(int capacity)\n    {\n        this.capacity = capacity;   \n    }\n\n    public void Enqueue(T item)\n    {\n        // todo: add synchronization mechanism\n        if (Count == capacity) RemoveLast();\n        AddFirst(item);\n    }\n\n    public T Dequeue()\n    {\n        // todo: add synchronization mechanism\n        var last = Last.Value;\n        RemoveLast();\n        return last;\n    }\n}\n</code></pre>\n\n<p>One thing to note is the default enumeration order will be LIFO in this example. But that can be overridden if necessary.</p>\n'}]
['https://Stackoverflow.com/questions/1292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192/']