C# Interview Question #38
What is the difference between IEnumerable<T> and ICollection<T>?
Generics & Collections Mid-Level Intermediate
Quick Interview Answer
IEnumerable<T> provides basic sequential enumeration. ICollection<T> extends IEnumerable<T> and represents a collection that exposes additional operations and information.
Detailed Explanation
IEnumerable<T> provides basic sequential enumeration. ICollection<T> extends IEnumerable<T> and represents a collection that exposes additional operations and information.
ICollection<T> includes members such as Count, Add, Remove, Clear, and Contains, although some implementations can be read-only.
Use IEnumerable<T> when consumers only need enumeration. Use ICollection<T> when collection-level operations or Count are part of the required contract.
Code Example
IEnumerable<string> sequence = new List<string>
{
"A", "B"
};
ICollection<string> collection = new List<string>
{
"A", "B"
};
collection.Add("C");
Console.WriteLine(collection.Count);