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
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.
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.
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);
}
}
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