Choosing collection interfaces
Choosing collection interfaces
Choose a collection interface according to what callers need to do, not according to the concrete container you happen to use.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; outputs are predictions pending compilation.
Enumerate without requiring an index
IEnumerable<T> lets a caller iterate through values with foreach. It does not promise a count, random access, repeatable enumeration or mutation. Accept this interface when a method needs only one pass. A list and an array can both supply that contract.
using System;using System.Collections.Generic;Console.WriteLine(Total(new int[] { 2, 4 }));Console.WriteLine(Total(new List<int> { 3, 5, 1 }));Console.WriteLine(Total(Array.Empty<int>()));static int Total(IEnumerable<int> values){ int sum = 0; foreach (int value in values) sum += value; return sum;}The method needs only enumeration; it works with both containers and returns zero for empty input.
Expected output (reasoned, not executed):
690Select the narrowest sufficient contract
IReadOnlyCollection<T> adds Count; IReadOnlyList<T> adds indexed reading. ICollection<T> exposes Count and mutation members, but implementations can be read-only. IList<T> adds positional access and editing; IDictionary<TKey,TValue> provides key-based lookup and updates. ISet<T> models uniqueness and set operations. A list preserves positional order and duplicates; a set is useful for membership and a dictionary associates keys with values.
using System;using System.Collections.Generic;IReadOnlyList<string> labels = new List<string> { "pen", "pen", "pad" };Console.WriteLine(labels.Count);Console.WriteLine(labels[1]);var stock = new Dictionary<string, int> { ["pen"] = 12 };Console.WriteLine(stock["pen"]);The two repeated labels are distinct positions; the dictionary instead retrieves a quantity by its key.
Expected output (reasoned, not executed):
3pen12Separate iteration from mutation
A List<T> enumerator is invalidated when the list is changed, including when an item is added. Do not edit that list while traversing it with foreach. Collect changes separately, use an appropriate removal method, or deliberately traverse a snapshot. SortedSet and SortedDictionary offer comparison-based ordering; LinkedList is useful for insertion or removal around a known node, not indexed lookup. Choose by operations and workload: list indexing is constant time, scanning a list is linear, and hash lookups depend on hashing quality.
using System;using System.Collections.Generic;var stock = new List<int> { 0, 4, 0, 7 };var available = new List<int>();foreach (int quantity in stock) if (quantity > 0) available.Add(quantity);Console.WriteLine(string.Join(",", available));Console.WriteLine(stock.Count);Only the destination changes, so the source enumeration stays valid.
Expected output (reasoned, not executed):
4,74Common mistakes and edge cases
Do not assume every enumerable has a Count property or that an interface promises a particular complexity. IReadOnlyList is not necessarily a snapshot. Do not use a dictionary enumeration order as a business rule. A list is not always slower than a hash table for tiny inputs; measure if performance matters.
Practice and next steps
Design a method that sums a sequence of positive quantities, preserving the source. Then choose interfaces for a positional playlist, a unique tag set and a product-to-stock map. Test an empty sequence and repeated quantities.
Next: Dictionary and HashSet equality.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Choosing collection interfaces — knowledge check
Apply the lesson concepts to the following scenarios.
Which input interface is sufficient for a one-pass total?
Which interface exposes Count and a readable integer index?
Which structure matches unique product IDs mapped to quantities?
What happens if a List<T> is structurally changed during foreach?
What does a read-only list interface guarantee?