Background: I’m trying to create my own “Vector” class to assist in performing mathematical calculations on groups of numbers. I am overloading the arithmetic operators ( + – * / ) to achieve the functionality that I want. At first, I used a private array in my class and then implemented the IEnumerable<T> interface. Afterwards, I thought of inheriting the List<T> class, but after reading a couple of articles, I understand that I should use Collection<T> instead. Please note that performance is very important when populating my “Vector” object with data.
Question: How does the Collection<T>.Add() method work? The List<T>.Add() documentation is very clear:
If Count already equals Capacity, the capacity of the List is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added.
However, the Collection<T>.Add() documentation says nothing at all about how it works. When I used List<T> as my base class I had access to the Capacity property and I was able to specify the size before using the Add() method. However, Collection<T> does not have a Capacity property—this is why I’m asking the question. Again, I reiterate: performance is very important.
Since performance is an issue, perhaps I should go back to using a private array and implementing the IEnumerable<T> interface. What do you think?
A
Collection<T>is a wrapper aroundIList<T>. The default constructor ofCollection<T>just uses a newList<T>, so theAddbehavior will be the same asList<T>assuming you use the default constructor.That’s because the
Addbehavior is dependent on the underlyingIList, which is passed in the constructor.Again, because that would depend on what the Collection is wrapping. It wraps the interface
IList<T>. The interface has no notion of capacity. There could be an implementation ofIList<T>that does not have a known capacity, like records in a database.If you need these implementation details such as capacity, then just use a
List<T>.Collection<T>has no performance benefits overList<T>since it is using one anyway. If performance is critical to you then you may want to find a library that has already solved this problem, rather than rolling your own.