C# - Foreach loop

A "foreach" loop in C# is a handy way to go through items in a collection, like an array or a list, one by one. It's simpler than using a regular "for" loop because you don't need to keep track of the index or the length of the collection. Here's how it works:

  1. You start with the keyword foreach.
  2. Then, you specify a variable to represent each item in the collection.
  3. After that, you use the keyword in followed by the name of the collection you're looping through.
  4. Inside the loop, you write the code you want to execute for each item.

Here's an example to make it clearer. Imagine you have a list of numbers, and you want to show or write down each number one by one. Here's how you could do it with a foreach loop:


using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}
	

In this example:

  • int[] numbers = { 1, 2, 3, 4, 5 }; creates an array of integers.
  • The foreach loop goes through each integer (number) in the numbers array.
  • Console.WriteLine(number); prints each number to the console.

When you run this code, the output will be:


1
2
3
4
5

For vs Foreach Loop Comparison

When comparing "for" and "foreach" loops in programming, we're looking at two different tools for iterating through items in collections like arrays or lists.

For Loop

  • The "for" loop is versatile, allowing you to specify the start point, the condition to keep going, and what happens after each loop (like increasing a counter).
  • It's useful when you need the item's index, want to change the iteration order, or don't need to check every item.
  • For example, to print elements from an array with even indices, a "for" loop is ideal.

Example:


for (int i = 0; i < array.Length; i++)
{
    // Do something with array[i]
}

Foreach Loop

  • The "foreach" loop is simpler, designed for when you need to access each item in a collection, one after another.
  • It eliminates the need to worry about the index or size of the collection, reducing the risk of errors.
  • Perfect for situations like printing every item in a list.

Example:


foreach (var item in collection)
{
    // Do something with item
}

In summary, use a "for" loop for more control over the iteration process, and a "foreach" loop for simplicity and ease when accessing every item in a collection.