Sobes.tech
Junior — Middle

What is the difference between different types of collection interfaces?

sobes.tech AI

Answer from AI

In C#, collection interfaces define different contracts for working with data sets, and their differences lie in functionality and purpose:

  • IEnumerable<T> — the basic interface for iterating over a collection using foreach. Allows only reading elements one by one.
  • ICollection<T> — extends IEnumerable<T>, adds methods for modifying the collection (Add, Remove), properties Count and IsReadOnly.
  • IList<T> — extends ICollection<T>, adds an indexer for access by index, methods for insertion and removal by index.
  • IDictionary<TKey, TValue> — represents a collection of key-value pairs, where access to elements is by key.

Thus, the choice of interface depends on the required operations: if only iteration is needed — IEnumerable<T>, if modification and counting are needed — ICollection<T>, if access by index is needed — IList<T>, if working with keys — IDictionary<TKey, TValue>.