enzom83
enzom83

Reputation: 8310

Implementing a collection using another collection

Often you have to implement a collection because it is not present among those of the .NET Framework. In the examples that I find online, often the new collection is built based on another collection (for example, List<T>): in this way it is possible to avoid the management of the resizing of the collection.

public class CustomCollection<T>
{
    private List<T> _baseArray;

    ...

    public CustomCollection(...)
    {
        this._baseArray = new List<T>(...);
    }
}
  1. What are the disadvantages of following this approach? Only lower performance because of the method calls to the base collection? Or the compiler performs some optimization?
  2. Moreover, in some cases the field relating to the base collection (for example the above _baseArray) is declared as readonly. Why?

Upvotes: 3

Views: 181

Answers (3)

Daniel Mann
Daniel Mann

Reputation: 58980

I'd say a pretty large disadvantage of this approach is that you can't use LINQ on your custom collection unless you implement IEnumerable. A better approach might be to subclass and force new implementation on methods as necessary, ex:

public class FooList<T> : List<T>
{
    public new void Add(T item)
    {
        // any FooList-specific logic regarding adding items
        base.Add(item);
    }
}

As for the readonly keyword, it means that you can only set the variable in the constructor.

Upvotes: -1

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

  1. The main disadvantage is the fact that if you want to play nice you'll have to implement a lot of interfaces by hand (ICollection, IEnumerable, possibly IList... both generic and non-generic), and that's quite a bit of code. Not complex code, since you're just relaying the calls, but still code. The extra call to the inner list shouldn't make too big of a difference in most cases.
  2. It's to enforce the fact that once the inner list is set, it cannot be changed into another list.

Usually it's best to inherit from one of the many built-in collection classes to make your own collection, instead of doing it the hard way. Collection<T> is a good starting point, and nobody is stopping you from inheriting List<T> itself.

Upvotes: 3

Joe
Joe

Reputation: 42577

For #2: if the private member is only assigned to in the constructor or when declared, it can be readonly. This is usually true if you only have one underlying collection and don't ever need to recreate it.

Upvotes: 2

Related Questions