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)
- {
-
- 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.
Let's have a look at how to use this collection in console application.
- static void Main(string[] args)
- {
- var trainings = new TrainingsCollection<Training>();
- trainings.Add(new Training { Name = "C#", Cost = 10 });
- trainings.Add(new Training() { Name = "Java", Cost = 10 });
-
-
- foreach (var item in trainings)
- {
- Console.Write($"Traning Name {item.Name} and cost {item.Cost}");
- }
-
- Console.ReadKey();
- }
Conclusion
Here we learned how to create your own custom generic collection with the help of Collection<T>, ICollection<T> and IEnumerator<T>. This Generic Collection gives you an advantage for your application with type-safe and saves a lot of time, avoiding duplication of code. You could also use of List<T> but there are many ways to implement type-safe generic collections in c#.