I came across the following code:
var collection = new Collection<string>();
I haven’t seen the Collection class used too much, and can’t find too much information about its purpose. Looking at the .NET Framework source, it’s pretty much just a wrapper around a List as it stores a List member field. Its constructor is as follows:
public Collection()
{
this.items = (IList<T>) new List<T>();
}
And it also implements IList. So you can declare the Collection as:
IList<string> collection = new Collection<string>();
Which to me is functionally equivalent to creating a List instead:
IList<string> collection = new List<string>();
So when would you ever want to use it over a List in your own code? I see that it is a base class for other .NET collections, but why would they include this as a public concrete (as opposed to internal and/or abstract)?
Regarding comments around possible duplicates — the answers to related questions seem to say that Collection class is supposed to be used as a base class. What I’m really asking that’s different is:
- If using in your own code, why not use List as a base class instead?
- Does it really ever make sense to instantiate a new Collection in
your own code in place of List? - If it really is only provided to serve as a base class, why is it not abstract?
I don’t really like answering my own questions, but as far as Q3 is concerned I believe I understand the reasoning. I got it while looking at this link referenced in Bas Paap’s answer.
In short, the reason the Collection class is not abstract is because you may want to leave yourself the option of deriving from the class at a later date. In the meantime, you can use it as a return type and instantiate it directly. The link shows a code example where this is the case.
I’ve upvoted all other answers that I thought addressed the issues raised in the question.