I need to keep a short history of values. So I need a list with a maximum number of items. And I want it to accept new addition even when it's full. In that case I want the oldest item I added to be lost. I did not find any class suiting this purpose then did my own. I will certainly add methods later on but for now I have what I need.
So my first question to you is: Is it a correct code: http://pastebin.com/0BCbyNqJ Does that class look clean enough to you?
And my second question is about these exceptions I am throwing.
/// <summary>
/// Oldest item added to the list
/// </summary>
public T First
{
get
{
if (_head < 0)
throw new IndexOutOfRangeException("The list is empty");
if (_firstRoundDone)
return _array[(_head + 1) % _max];
else
return _array[0];
}
}
Before anything is added to my list, I would like calls to First
, Last
and Count
to return null. I think that would make more sense. But I don't know how to do so since the return types are int or T, for which I don't want to add a constraint like where T:Nullable
.
As I don't see any solution I wonder if the Exception is not, afterall, the most elegant way. Or should I implement methods like GetFirst(out T first)
or even TryGetFirst(out T)
?
Extending Queue<>
would produce a very short code, like this:
public class Buffer<T> : Queue<T>
{
private int? maxCapacity { get; set; }
public Buffer() { maxCapacity = null; }
public Buffer(int capacity) { maxCapacity = capacity; }
public void Add(T newElement)
{
if (this.Count == (maxCapacity ?? -1)) this.Dequeue(); // no limit if maxCapacity = null
this.Enqueue(newElement);
}
}
.Clear()
and .ToList()
would be inherited, no need to implement them.
Consider publicly available LRU caches such as http://code.google.com/p/csharp-lru-cache/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With