Customise your list by overriding Collection of T with C# .NET

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:

collection[2] = 3;

Collection.Clear will call into the protected ClearItems methods that you can override. Removing an item by an index can be controlled by overriding the RemoveItem method:

OK, added: 2, position: 0
OK, added: 10, position: 1
OK, added: 8, position: 2
Out of bounds: 40
Out of bounds: 23
Clearing all items at once is a big no-no!
That’s not going to happen, buddy! Removing an item at index 0 is not allowed.
That’s not going to happen, buddy! Removing an item at index 0 is not allowed.
OK, removed from index 2

That should be easy to follow I hope. The only peculiar thing might be that ris.Remove(2) wasn’t allowed. The reason is that the element 2 is found in position 0 so it’s the same as calling ris.RemoveAt(0).