Course Content
C# Tutorial
About Lesson

Iterating through collections (foreach)

Iteration lies at the heart of efficient programming, especially when working with collections in C#. Embracing the foreach loop offers a streamlined approach to traverse arrays, lists, and other enumerable objects, unlocking the full potential of your code.

Understanding the foreach Loop

The foreach loop in C# simplifies the process of iterating through collections by abstracting the complexities of indexing and iteration logic. Unlike traditional for or while loops, it offers a more concise and readable syntax.

Syntax Demystified

foreach (var item in collection)
// Perform operations with 'item'

Here, item represents each element within the collection during each iteration, allowing seamless access to its properties and functionalities.

Leveraging with Collections


Arrays, fundamental data structures in C#, integrate effortlessly with foreach loops:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (var num in numbers)
// Process 'num'


Lists, dynamic arrays, also benefit from foreach loops:

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

foreach (var name in names)
// Utilize 'name'

Benefits and Best Practices

Readability and Simplicity

The foreach loop enhances code readability by emphasizing the intent of iteration without managing explicit indexes or conditions.

Safety in Immutable Collections

When working with immutable collections or scenarios where altering collection size isn’t permitted, foreach shines by ensuring safer iteration.

Increased Performance

For collections utilizing complex iterators or third-party enumerators, foreach often outperforms traditional loops.

Caveats and Considerations

No Access to Index

Unlike for loops, foreach doesn’t expose the current index by default, restricting direct manipulation of index values within the loop.

Modification Constraints

When iterating over a collection, direct modifications (additions or deletions) to the collection can cause runtime exceptions