Introduction
This article will demonstrate how to create your own custom collection class using generic Collection<T>. It will also demonstrate how to implement ICollection<T> and IEnumerator<T> in order to create a generic, type-safe, and expandable collection class.
Let's start with a step by step approach to first learn Collection<T> and then ICollection<T> and IEnumerator<T> .
Prerequisites
Learn how to create your own custom collection class with help of System.Collection.Generics and customize your collection to add common type of validation in one place.
Using Collection<T>
Let's have class training with a few properties and then make a collection of that class. The generic Collection<T> is basically derived from ICollection<T> where most of the implementations are taken care of for you and you do not need to worry about addition and removal etc. if you want to customize addition and removal use ICollection<T> directly which is step2 in this article.
- public class Training
- {
- public string Name { get; set; }
- public int Cost { get; set; }
- }
- public class Trainings : Collection<Training>
- {
- public Training this[string name]
- {
- get { return this.Items.First(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)); }
- }
- public IEnumerable<string> All => this.Items.Select(s => s.Name);
- protected override void InsertItem(int index, Training item)
- {
- // validation before adding in common place.
- if (item.Cost > 0)
- {
- base.InsertItem(index, item);
- }
- }
- public void ForEach(Action<string> action)
- {
- foreach (var item in Items)
- {
- action($"Traning Name {item.Name} and cost {item.Cost}");
- }
- }
- }
You may notice that you have your indexer to get by name and validation before inserting a new item. Let's have a look at how to use this collection in console application.

Join the conversation! Your thoughts help the community grow.