Reputation: 8310
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>(...);
}
}
_baseArray
) is declared as readonly
. Why?Upvotes: 3
Views: 181
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
Reputation: 65116
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
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