Back to course

Foreach Loop and Collection Iteration

.NET Zero to Hero: Master C# and Modern App Development

The Foreach Loop

foreach is a cleaner way to loop through arrays or collections. It reads "for each item in the collection".

Example:

csharp string[] names = {"Alice", "Bob", "Charlie"};

foreach (string name in names) { Console.WriteLine($"Hello {name}"); }

Note: Use foreach when you don't need the index (i.e., you don't need to know if it's the 1st or 2nd item). Use for if you need to modify the array at a specific index.