How do I override List’s Add method in C#?

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.

Leave a Comment