A foreach loop is used to iterate over each element in a collection, such as an array or list, without needing to manage the loop counter manually.
Click to reveal answer
beginner
How does a foreach loop differ from a for loop?
A foreach loop automatically accesses each element in a collection one by one, while a for loop requires manual control of the index to access elements.
Click to reveal answer
intermediate
Can you modify the elements of a collection inside a foreach loop in C#?
No, you cannot modify the elements directly inside a foreach loop because the loop variable is read-only. To modify elements, use a for loop or other methods.
Click to reveal answer
beginner
Write a simple foreach loop to print all items in a string array named fruits.
Example:
string[] fruits = {"apple", "banana", "cherry"};
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
Click to reveal answer
intermediate
What types of collections can be used with a foreach loop in C#?
Any collection that implements IEnumerable or IEnumerable<T> can be used with foreach, including arrays, lists, dictionaries, and custom collections.
Click to reveal answer
Which keyword is used to iterate over each element in a collection in C#?
Aforeach
Bwhile
Cdo
Dswitch
✗ Incorrect
The foreach keyword is designed to loop through each element in a collection easily.
What happens if you try to modify the loop variable inside a foreach loop?
AIt modifies the original collection element
BIt skips the current iteration
CIt causes a compile-time error
DIt modifies a copy of the element only
✗ Incorrect
The loop variable in a foreach loop is read-only. Attempting to assign a new value to it causes a compile-time error.
Which of these collections can be used with foreach?
AArray
BAll of the above
CDictionary
DList
✗ Incorrect
All these collections implement IEnumerable and can be iterated with foreach.
What is the correct syntax to start a foreach loop over a collection named items?
Aforeach (var item in items) { }
Bforeach (items in var item) { }
Cforeach item in items { }
Dforeach (items : item) { }
✗ Incorrect
The correct syntax is foreach (var item in items) { }, where item is the loop variable.
Can foreach be used to iterate over a string in C#?
AOnly if converted to a char array first
BNo, strings cannot be iterated
COnly in .NET 6 and later
DYes, because a string is a collection of characters
✗ Incorrect
Strings implement IEnumerable<char>, so you can use foreach to iterate over each character.
Explain how a foreach loop works in C# and when you would use it.
Think about how you would read items from a list one by one.
You got /4 concepts.
Describe the limitations of modifying collection elements inside a foreach loop and how to handle such cases.
Consider why the loop variable is a copy and what alternatives exist.
You got /4 concepts.
Practice
(1/5)
1. What does a foreach loop do in C#?
easy
A. It visits each item in a collection one by one.
B. It creates a new collection from scratch.
C. It only runs once regardless of collection size.
D. It deletes items from a collection while looping.
Solution
Step 1: Understand the purpose of foreach
The foreach loop is designed to go through each element in a collection without manual index handling.
Step 2: Compare options to foreach behavior
Only It visits each item in a collection one by one. correctly describes visiting each item one by one. Other options describe actions foreach does not perform.
Final Answer:
It visits each item in a collection one by one. -> Option A
Quick Check:
foreach loops = visit items one by one [OK]
Hint: Foreach always processes every item in the collection [OK]
Common Mistakes:
Thinking foreach modifies the collection
Confusing foreach with creating collections
Assuming foreach runs only once
2. Which of the following is the correct syntax for a foreach loop over a list of strings named names?
easy
A. foreach (name string in names) { Console.WriteLine(name); }
B. foreach (string name in names) { Console.WriteLine(name); }
C. foreach string name in names { Console.WriteLine(name); }
D. foreach (string name : names) { Console.WriteLine(name); }
Solution
Step 1: Recall correct foreach syntax
The correct syntax uses parentheses with type and variable, then 'in' keyword before collection.
Step 2: Check each option
foreach (string name in names) { Console.WriteLine(name); } matches correct syntax. foreach string name in names { Console.WriteLine(name); } misses parentheses. foreach (name string in names) { Console.WriteLine(name); } swaps type and variable. foreach (string name : names) { Console.WriteLine(name); } uses ':' which is invalid in C# foreach.
Final Answer:
foreach (string name in names) { Console.WriteLine(name); } -> Option B
Quick Check:
foreach syntax = (type variable in collection) [OK]
Hint: Remember: foreach uses (type variable in collection) [OK]
Common Mistakes:
Omitting parentheses
Using ':' instead of 'in'
Swapping variable and type order
3. What will be the output of this code?
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
Console.Write(fruit + " ");
}
medium
A. apple banana cherry
B. applebanana cherry
C. apple, banana, cherry
D. apple
banana
cherry
Solution
Step 1: Understand the loop behavior
The foreach loop prints each fruit followed by a space, all on the same line.
Step 2: Analyze output format
Since Console.Write (not WriteLine) is used, output is continuous with spaces between fruits.
Final Answer:
apple banana cherry -> Option A
Quick Check:
foreach prints items with space = apple banana cherry [OK]
Hint: Console.Write prints inline; spaces separate items [OK]
Common Mistakes:
Assuming Console.WriteLine adds spaces
Expecting commas between items
Thinking output is on separate lines
4. Identify the error in this code snippet:
List<int> numbers = new List<int> {1, 2, 3};
foreach (int num in numbers)
{
numbers.Remove(num);
}
medium
A. Variable 'num' is not declared.
B. Missing semicolon after foreach statement.
C. Cannot modify collection while iterating with foreach.
D. List initialization syntax is incorrect.
Solution
Step 1: Understand foreach restrictions
Modifying a collection (like removing items) while using foreach causes runtime errors.
Step 2: Check other options
Semicolon is not needed after foreach header. Variable 'num' is declared. List initialization is correct.
Final Answer:
Cannot modify collection while iterating with foreach. -> Option C
5. Given a dictionary Dictionary<string, int> scores, how can you use a foreach loop to print all keys with values greater than 50?
hard
A. foreach (var pair in scores) { Console.WriteLine(pair.Value > 50); }
B. foreach (string key in scores.Values) { if (key > 50) Console.WriteLine(key); }
C. foreach (int value in scores.Keys) { if (value > 50) Console.WriteLine(value); }
D. foreach (var pair in scores) { if (pair.Value > 50) Console.WriteLine(pair.Key); }
Solution
Step 1: Understand dictionary iteration
Iterating a dictionary with foreach gives key-value pairs as 'var pair'.
Step 2: Filter and print keys with values > 50
Check pair.Value > 50, then print pair.Key. foreach (var pair in scores) { if (pair.Value > 50) Console.WriteLine(pair.Key); } does this correctly.
Step 3: Analyze incorrect options
foreach (string key in scores.Values) { if (key > 50) Console.WriteLine(key); } tries to iterate values as strings (wrong). foreach (int value in scores.Keys) { if (value > 50) Console.WriteLine(value); } iterates keys as ints (wrong). foreach (var pair in scores) { Console.WriteLine(pair.Value > 50); } prints booleans, not keys.
Final Answer:
foreach (var pair in scores) { if (pair.Value > 50) Console.WriteLine(pair.Key); } -> Option D
Quick Check:
Use var pair and check Value > 50 [OK]
Hint: Use var pair to access key and value in dictionary [OK]
Common Mistakes:
Iterating keys as values or vice versa
Printing booleans instead of keys
Wrong variable types in foreach
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.