Recall & Review
beginner
What is the purpose of a
foreach loop in C#?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:<br>
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#?
✗ 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?✗ 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?✗ 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?✗ 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#?✗ 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.