How do I override List<T>'s Add method in C#?

77,995

Solution 1

First, you can't override Add and still have polymorphism against List, meaning that if you use the new keyword and your class is cast as a List, your new Add method won't be called.

Second, I suggest you look into the Queue class, as what you are trying to do is more of a queue than it is a list. The class is optimized for exactly what you want to do, but does not have any sort of a size limiter.

If you really want something to act like a List but work like a Queue with a maximum size, I suggest you implement IList and keep an instance of a Queue to store your elements.

For example:

public class LimitedQueue<T> : IList<T>
{
  public int MaxSize {get; set;}
  private Queue<T> Items = new Queue<T>();
  public void Add(T item)
  {
    Items.Enqueue(item);
    if(Items.Count == MaxSize)
    {
       Items.Dequeue();
    }
  }
  // I'll let you do the rest
}

Solution 2

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.

Solution 3

You can't override Add(), it is not a virtual method. Derive from IList instead and use a private Queue member for the implementation.

Solution 4

You could extend System.Collections.ObjectModel.Collection and override the InsertItem method to get the behaviour you want, and it also implements IList

Solution 5

You can just write a class that implements IList<T> that holds an internal List<T> and write your own methods.

Share:
77,995
shinyhappydan
Author by

shinyhappydan

Sexy fit hair

Updated on September 05, 2021

Comments

  • shinyhappydan
    shinyhappydan over 2 years

    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 already 10 items in the list, then the first item would be removed before the new item was appended.

    What I want to do is create a class that extends System.Collections.Generic.List<T>, and then modifies the Add(T item) method to include the functionality which removes the first item if necessary.