0

Say I want a list of values with a name and I already have

interface INamedItem
{
  string Name { get }
}

Would I implement it like this:

class NamedValueList : List<ValueType>, INamedItem
{
  public string INamedItem.Name { get; set }
  ...
}

or would I rather have it implement IList?

class NamedValueList : IList<ValueType>, INamedItem
{
  public string INamedItem.Name { get; set }
  private List<ValueType> _list = new List<ValueType>();
  public Add(ValueType value)
  {
    _list.Add(value);
  }
 ...
}

One way I'm open for any IList implementation, the other way I have to relay every IList call to my List object which seems not very efficient if I just want the list to have a name.

Or would I even implement IList myself instead of relaying the calls to my List object?

Is this pure preference or are there any good reasons to pick one of the solutions over the other?

Piglet
  • 27,501
  • 3
  • 20
  • 43
  • 1
    You might want to consider some of the arguments in this question: [Why not inherit from List?](https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt) – ProgrammingLlama Aug 07 '23 at 09:29
  • 1
    You don't want to change/extend the behavior of the list, so don't inherit from it. Just have a list in your class and expose the properties and methods that you need. – Tim Schmelter Aug 07 '23 at 09:30
  • 1
    My own arguments against: 1. If you're serializing to JSON then there isn't a good way to represent this list-with-properties and you'd probably end up serializing it as an object with a child array of items (via a converter to handle the custom type). 2. It seems like adding a property to a list (at least in some cases) is a slippery slope for it containing more information, and then it has a role as a list, and also a role describing some parent object that it somehow also is. I agree with Tim's suggestion of having a class with the name, and then a list within that class. – ProgrammingLlama Aug 07 '23 at 09:34
  • 2
    In addition: if you want to enumerate your class like it was a list, you can do it without having to inherit from list, simply provide a `GetEnumerator` method, then you can use `foreach`. – Tim Schmelter Aug 07 '23 at 09:44
  • @TimSchmelter thanks. but if I have a List field in my class and I implement GetEnumerator, Add, Remove and anything else I need which is basically all IList provides, woudl I not actually implement IList as in my second snippet? I mean in the end I want a List with a name so it should provide the same functionality as List plus a name. I get that inheriting from List would take away the abstraction by IList so is there anything wrong with forwarding all those IList methods to my List field? – Piglet Aug 07 '23 at 10:49

0 Answers0