Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding List<T>'s Add()

Tags:

c#

collections

Can't i overload List's Add method ?

class ListDemo<T>:List<T>
 {
    public override T  Add<T>(T value)
   {
      return base.Add(value);
   }
}

I am receiving the following error :

1) Type parameter 'T' has the same name as the type parameter from outer type 'CollectionsExample.ListDemo

2) 'CollectionsExample.ListDemo.Add(T)': no suitable method found to override

like image 391
user196546 Avatar asked Oct 26 '09 17:10

user196546


3 Answers

Instead of subclassing from List<T>, you should encapsulate List<T> and implement IList<T>. This makes it easy to handle "overriding" the behavior of Add:

public class ListDemo<T> : IList<T>
{
    private List<T> list = new List<T>(); // Internal list
    public void Add(T item)
    {
       // Do your pre-add logic here
       list.Add(item); // add to the internal list
       // Do your post-add logic here
    }

    // Implement all IList<T> methods, just passing through to list, such as:
}

List<T> should not be part of your public API - it should be an implementation detail.

like image 181
Reed Copsey Avatar answered Nov 20 '22 15:11

Reed Copsey


The correct code is:

class ListDemo<T>:List<T>
{
    public new void Add(T value)
    {
      base.Add(value);
    }
}

You don't need a type parameter on both the class declaration and the method. It is the class declaration that is generic in this case; so when you try to declare the Add method as taking a generic type parameter named T, the compiler will complain that you are trying to have 2 type parameters with the same name.

Edit: Fixed the code sample. Since Add is not virtual, it cannot be overridden with the override keyword (so the original sample would actually not compile). You can still declare it using new, but that could lead to different meaning of your Add method. I would strongly consider just implementing IList<T>, as suggested in the comments.

like image 26
driis Avatar answered Nov 20 '22 16:11

driis


This worked for me (based on Sam Harwell's comment):

public class ListDemo<T> : Collection<T>
{
    protected override void InsertItem(int index, T item)
    {
        // Your add condition ...
        if (!this.Any(x => ...))
            base.InsertItem(index, item);
    }
}
like image 4
IngoB Avatar answered Nov 20 '22 17:11

IngoB