-1

I'm trying to create an excel document generator project. Currently i'm working on cell styles part.

So i have next structure:

public class Styles : List<Style>, ISerializableClass
{
    ...some special methods...
}

The thing i want to achieve:

When some Style ( item ) is being added to the Styles i want to automatically add/modify/update the Style id.

In other words i want to override the base list.Add() behavior. How can i achieve this?

Or i just should add this method in my Styles class:

public void Add(Style style)
    {
        /*
         * Some mu logic
        */
        base.Add(style);
    }

To hide the default List.Add() method?

Developer
  • 4,158
  • 5
  • 34
  • 66

1 Answers1

2

The best practice is to implement IList<T> yourself instead of inheriting from List<T>. You can then delegate most of the implementation to a List<T> field:

public class Styles : IList<Style>, ISerializableClass
{
    private List<Style> _list = new List<Style>();

    public void Add(Style style)
    {
        // Your stuff here
        _list.Add(style);
    }

    // ...
}

See this question for more details about why inheriting from List<T> is not a good idea.

And you should almost always avoid hiding base class methods. Because this is easily defeated with code such as:

var stylesList = new Styles(); // Suppose this hides List<T>.Add
var castedList = (IList<Styles>)stylesList;
castedList.Add(new Style()); // <-- this still calls List<T>.Add

IMHO, the only acceptable use case for method hiding is in situations like IEnumerable<T>.GetEnumerator() hiding IEnumerable.GetEnumerator() where both methods do exactly the same thing anyway.

Community
  • 1
  • 1
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
  • Aha... Thanks, both your suggestion and a link gave me a good amount of info to think about. You helped me. – Developer May 04 '15 at 18:42