0

(In a C# program) I have a List<Author> authors, where Author is a class I wrote. Lists have a default Add(Object o) method, but I need to make it either less accessible or overwrite it for specifically my authors object.

So far, I've found information on polymorphism, extension methods (like this one), and delegates in combination with dynamic objects, but I'm not sure if what I'm asking is possible in the first place without keeping things simple and creating a new class that inherits from List<Author> (I figure that even that doesn't make sense, given that I would only use the class once).

Note that unlike this scenario, I don't have access to the List<T> class, so I can't make the method virtual or partial, or create an overflow that hides the original method.

Given the situation, how would I make the existing Add(Object o) method private and overwrite it with a public method? Is the best solution the separate class, or something more complicated?

Community
  • 1
  • 1
jmindel
  • 465
  • 1
  • 7
  • 16

2 Answers2

0

You want to roll your own class in this instance with the new Add method

class MyCustomList<T> : List<T>
{
    public new void Add(T item)
    {
        //your custom Add code here
        // .... now add it..
        base.Add(item);
    }
}

Instantiate it with something like this:

MyCustomList<Author> sam = new MyCustomList<Author>;

Hope that helps.

Sergio S
  • 194
  • 7
  • Thanks! I suppose that works. I was hoping there was something that didn't require creating a new class, but I'll use this for now. – jmindel Dec 15 '15 at 19:29
0

I think the best solution is to encapsulate the List in its own class. The best option is to write your own collection, backed by a list. Then you can add your custom logic to the add method.

Example:

public class AuthorCollection : IList<Author>
{
    private IList<Author> backingAuthorList;

    public AuthorCollection(IList<Author> backingAuthorList)
    {
        if (backingAuthorList == null)
        {
            throw new ArgumentNullException("backingAuthorList");
        }

        this.backingAuthorList = backingAuthorList;
    }

    public void Add(Author item)
    {
        // Add your own logic here

        backingAuthorList.Add(item);
    }
}
Daniel L
  • 26
  • 3