I am currently looking to make my own collection, which would be just like a regular list, except that it would only hold 10 items. If an item was added when there were alre
Your description of your requirement sounds like a Circular Buffer.
I implemented my own - similar to this implementation on CodePlex except that mine implements IList<T>
.
Some of the other answers suggest using a Queue<T>
- but this isn't quite the same thing, as it only allows FIFO access.
As a general point, it's not recommended to derive from List<T>
- instead derive from Collection<T>
, and implement any additional stuff you need. But for a circular buffer it's probably more appropriate to use a private array rather than deriving from Collection<T>
like the CodePlex implementation.
You could extend System.Collections.ObjectModel.Collection and override the InsertItem method to get the behaviour you want, and it also implements IList
It seems like the best I can do is this:
class MostRecentList<T> : System.Collections.Generic.List<T> {
private int capacity;
public MostRecentList(int capacity) : base() {
this.capacity = capacity;
}
public new void Add(T item) {
if (base.Count == capacity) {
base.RemoveAt(0);
}
base.Add(item);
}
}
Since the add()
method is not marked as virtual.
You can also implement the add method via
public new void Add(...)
in your derived class to hide the existing add and introduce your functionality.
Edit: Rough Outline...
class MyHappyList<T> : List<T>
{
public new void Add(T item)
{
if (Count > 9)
{
Remove(this[0]);
}
base.Add(item);
}
}
Just a note, figured it was implied but you must always reference your custom list by the actual type and never by the base type/interface as the hiding method is only available to your type and further derived types.
You could take a look at the C5 collection library. They have an ArrayList<T> that implements IList<T> and have a virtual Add method. The C5 collection library is an awesome collection of lists, queues, stacks etc... You can find the C5 library here:
http://www.itu.dk/research/c5/
You can't override Add(), it is not a virtual method. Derive from IList instead and use a private Queue member for the implementation.