Junior — Middle
What collection object types are suitable for iteration using a foreach loop?
sobes.tech AI
Answer from AI
In C#, the foreach construct is used with collections that implement the IEnumerable or IEnumerable<T> interface. This means you can iterate over:
- Arrays (e.g.,
int[],string[]) - Lists (
List<T>) - Sets (
HashSet<T>) - Dictionaries (
Dictionary<TKey, TValue>) — iterating over key-value pairs - Any other collections that implement
IEnumerable
Example:
List<string> names = new List<string> { "Anna", "Boris", "Victor" };
foreach (var name in names)
{
Console.WriteLine(name);
}
Thus, foreach is convenient for iterating over any collections that support enumeration.