What is ICollection in C#: Definition and Usage
ICollection in C# is an interface that defines size, enumeration, and modification methods for collections. It acts like a basic container that supports adding, removing, and counting items, and is a building block for many collection types.How It Works
Think of ICollection as a simple box that can hold items. It tells you how many items are inside, lets you add or remove items, and allows you to look through all the items one by one. It does not care about the order or how the items are stored inside.
In programming, ICollection is an interface, which means it only defines what actions a collection should support, but not how to do them. Different types of collections like lists, sets, or queues can implement ICollection to provide these basic features in their own way.
Example
This example shows how to use ICollection<string> to add, remove, and count items in a collection.
using System; using System.Collections.Generic; class Program { static void Main() { ICollection<string> fruits = new List<string>(); fruits.Add("Apple"); fruits.Add("Banana"); fruits.Add("Cherry"); Console.WriteLine($"Count: {fruits.Count}"); fruits.Remove("Banana"); Console.WriteLine("Fruits after removal:"); foreach (var fruit in fruits) { Console.WriteLine(fruit); } } }
When to Use
Use ICollection when you want a simple way to work with groups of items that can be counted, added to, or removed from. It is useful when you want to write code that can work with many types of collections without caring about their specific details.
For example, if you write a method that processes a list of users, you can accept an ICollection<User> parameter. This way, the method can work with any collection type like a list, set, or custom collection, as long as it supports the basic collection actions.
Key Points
ICollectionis a basic interface for collections in C#.- It supports adding, removing, counting, and enumerating items.
- Many collection types implement
ICollectionto provide these features. - It helps write flexible code that works with different collection types.
Key Takeaways
ICollection defines basic collection operations like add, remove, and count.ICollection to write flexible code that works with many collection types.ICollection.