0
0
C Sharp (C#)programming~10 mins

Foreach loop over collections in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Foreach loop over collections
Start with collection
Pick first item
Execute loop body with item
More items?
NoExit loop
Yes
Pick next item
The foreach loop picks each item from a collection one by one and runs the loop body using that item until all items are processed.
Execution Sample
C Sharp (C#)
string[] fruits = {"apple", "banana", "cherry"};
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
This code prints each fruit name from the fruits array, one per line.
Execution Table
IterationCurrent item (fruit)ActionOutput
1"apple"Print fruitapple
2"banana"Print fruitbanana
3"cherry"Print fruitcherry
--No more items, exit loop-
💡 All items in the collection have been processed, so the loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
fruitnull"apple""banana""cherry"null (loop ended)
Key Moments - 3 Insights
Why does the variable 'fruit' change each iteration?
Because foreach assigns the next item from the collection to 'fruit' each time, as shown in execution_table rows 1 to 3.
What happens when all items are done?
The loop stops automatically, as shown in the last row of execution_table where no more items remain.
Can we modify the collection inside the foreach loop?
No, modifying the collection during foreach can cause errors or unexpected behavior. The loop expects the collection to stay the same.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'fruit' during iteration 2?
A"cherry"
B"apple"
C"banana"
Dnull
💡 Hint
Check the 'Current item (fruit)' column at iteration 2 in the execution_table.
At which iteration does the foreach loop stop?
AAfter iteration 1
BAfter iteration 3
CAfter iteration 2
DIt never stops
💡 Hint
Look at the exit_note and the last row in execution_table showing no more items.
If we add "date" to the fruits array, how many iterations will the loop have?
A4
B3
C5
DCannot tell
💡 Hint
The loop runs once per item in the collection, so adding one item increases iterations by one.
Concept Snapshot
foreach (type var in collection) {
  // use var inside loop
}

- Loops over each item in collection
- 'var' holds current item
- Stops after last item
- Collection should not change during loop
Full Transcript
The foreach loop in C# goes through each item in a collection one by one. It assigns the current item to a variable and runs the loop body using that item. When all items are done, the loop stops automatically. You cannot change the collection while looping. This example prints each fruit name from an array. The variable 'fruit' changes each iteration to the next fruit. The loop ends after the last fruit is printed.