Foreach Loop in C#
483
09-Jun-2024
Ravi Vishwakarma
09-Jun-2024The foreach loop in C# is used to iterate over a collection of items, such as arrays, lists, or other enumerable collections. It is beneficial for iterating through elements without knowing the collection size or managing loop counters. The foreach loop provides a cleaner and more readable way to traverse collections than the traditional for loop.
Here is the basic syntax of a foreach loop in C#:
Example Usage
Iterating Over an Array:
Iterating Over a List:
Key Points
foreachloop can only be used with collections that implement theIEnumerableinterface.itemin the examples) is read-only within the scope of the loop. You cannot assign a new value toitemwithin the loop body.foreachloop automatically handles the iteration bounds, so you do not need to manage index variables manually.forloop with index variables, especially when working with collections that can change in size or when the iteration logic is complex.Limitations
foreachloop. Doing so will result in anInvalidOperationException.forloop or other appropriate methods that provide access to the collection by index.