C# foreach Loop with Examples
How to write "foreach" loop in C# with some examples

Programs basically live in loops most of the time.
In C#, we’ve got the foreach-loop, which comes with its own perks and a much cleaner look.
This loop lets us look at every item one by one without having to mess around with an index. Since there aren’t any indexes to track, the whole thing stays way simpler.
That’s a huge win for making your code easier to follow and wrap your head around.
Quickstart with foreach-loop in C#
The foreach-loop grabs every item in order, which is just a fancy way of saying Enumeration in C# universe.
By doing this, we ditch those annoying bugs that pop up when you mess up your index math.
Let’s consider following scenario.
- First, we set up an array of string with 5 items, filling each one with your favorite Avenger member.
- Next, we fire up a
foreachloop to cycle through everything in that array. You can name the current item whatever you like. We’ll just call itheroto work with it. - Finally, we just grab that string inside the loop body. The
foreach-loop is super reliable and always hands them over in the exact order they’re stored.
using System;
// Step 1: create an array of 5 The Avengers members.
string[] avengers =
{
"Iron Man",
"Spider-Man",
"The Hulk",
"Captain America",
"Black Widow"
};
// Step 2: loop with the foreach keyword.
foreach (var hero in avengers)
{
// Step 3: access the enumeration variable aka the Hero name.
Console.WriteLine($"Avengers Assemble: {hero}");
}
// OUTPUT:
// Avengers Assemble: Iron Man
// Avengers Assemble: Spider-Man
// Avengers Assemble: The Hulk
// Avengers Assemble: Captain America
// Avengers Assemble: Black Widow
Conclusion
As usual, if you have any questions or a better method, leave a comment below. Thanks for reading, and see you next time!
