I am trying to create my own Circular Buffer in C#. I am using a counter to keep track of where I need to insert the next item. Here is a Link to the full code and here is the (simplified) code to do so:
public class CircularBuffer<T>
{
private bool _isFull = false;
private int _size;
private int _current = 0;
private BufferItem<T>[] _buffer;
public CircularBuffer(int size)
{
_size = size;
_buffer = new BufferItem<T>[size];
}
public void Insert(T value)
{
BufferItem<T> item = new BufferItem<T>(value);
//Removed code to check if the buffer is full, if so over-write the oldest item
//and don't insert at the current position
_buffer[_current] = item;
_isFull = (_current == (_size - 1));
_current++;
//Age all items
}
It all works fine and dandy until after I increment the current position and try to add another item:

Here I added the item "first" and the current position (_current) is incremented.

I added the item "third" but the current position gets reset to 0. There is absolutely no other code including _current other than declaring it, accessing it and incrementing it.
What in the world is going on? Here is the code for BufferItem<T>:
public class BufferItem<T>
{
public int Age = 0;
public T Item;
public BufferItem(T item)
{
Item = item;
}
}
Your class methods are fine. Your
_currentvariable works fine, too. The issue lies outside of theCircularBufferclass. Somewhere where this is being implemented, the CircularBuffer object in question is getting reset in some way.