Customise your list by overriding Collection of T with C# .NET
December 5, 2016 3 Comments
Imagine that you’d like to build a list type of collection where you want to restrict the insertion and/or deletion of items in some way. Let’s say we need an integer list with the following rules:
- The allowed range of integers is between 0 and 10 inclusive
- A user should not be able to remove an item at index 0
- A user should not be able to remove all items at once
One possible solution is to derive from the Collection of T class. The generic Collection of T class in the System.Collections.ObjectModel namespace provides virtual methods that you can override in your custom collection.
The virtual InsertItem and SetItem methods are necessary to control the behaviour of the Collection.Add and the way items can be modified through an indexer:
