Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 454
enzom83 Avatar asked Jun 22 '26 17:06

enzom83


2 Answers

  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.

like image 136
Matti Virkkunen Avatar answered Jun 25 '26 06:06

Matti Virkkunen


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.

like image 32
Joe Avatar answered Jun 25 '26 06:06

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!