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

Foreach loop over collections in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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#?
Aforeach
Bwhile
Cdo
Dswitch
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
Which of these collections can be used with foreach?
AArray
BAll of the above
CDictionary
DList
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) { }
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
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.