Mid Collections

What does ICollection<T> provide, and how does it differ from IEnumerable<T>?

ICollection<T> extends IEnumerable<T> and adds features like:

  • Counting (Count property)
  • Adding and removing items (Add, Remove)
  • Checking for existence (Contains)

Difference:

  • IEnumerable<T> is read-only and forward-only iteration.
  • ICollection<T> adds modification capabilities.

Example:

ICollection<int> numbers = new List<int>();

numbers.Add(5);

numbers.Remove(5);

Console.WriteLine(numbers.Count);

Real-world use case:

Use ICollection<T> when you need to manipulate the collection (add/remove items),

such as managing an in-memory cart of products in a shopping application.

More from C# Programming Tutorial

All questions for this course