views:

50

answers:

2

What I need is a collection where i can specify the max number of elements. If i try to insert an element and the collection is full. The first element in the collection is removed, so that it does not overflow.

Is there such an object in .net or do i have to make it myself?

+1  A: 

There is no existing collection in .NET that provides a circular/cyclic buffer implementation. You will have to roll it yourself.

Also, see a related question on SO here: http://stackoverflow.com/questions/590069/how-would-you-code-an-efficient-circular-buffer-in-java-or-c

Wim Hollebrandse
+3  A: 

You can extend Queue class in order to do it.

For example:

public class MaxQueue : Queue
{
    private int maxItems;

    public MaxQueue(int maxItems)
    {
        this.maxItems = maxItems;
    }

    public override void Enqueue(object obj)
    {
        if(Count == maxItems)
        {
            Dequeue();
        }

        base.Enqueue(obj);
    }
}

(this example is very naive. It is not thread safe, it doesn't check the maxItems is at least 1. It is based on Queue so you're safe to know you dequeued the first item added to it)

Elisha