C# Foreach

In-depth concept of 'foreach' loop in C#.

* 'IEnumerable' and 'IEnumerable<T>' are both interfaces that define a way to iterate over a collection of objects. However, there are some key differences between them.

Foreach Loop

The 'foreach' loop is used to iterate over elements in a collection, such as an array, list, or any other type that implements the 'IEnumerable' or 'IEnumerable<T> interface. The 'foreach' loop simplifies the process of iterating through elements, providing a cleaner and more concise syntax than using a traditional for loop.

Here's the basic syntax of a 'foreach' loop in C#:

foreach (var item in collection)
{
    // Code to be executed for each item in the collection
}

Here, 'collection' is the iterable object, and 'item' is a variable that represents the current element in each iteration. The type of 'item' is inferred based on the type of elements in the collection.

Here's an example using an array:

cs Copy Code
using System;

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

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

    }
}

Here, the 'foreach' loop iterates over each element in the 'numbers' array, and the value of each element is printed to the console.

Output:
1
2
3
4
5

Simplify the collection list: int[] numbers = [1, 2, 3, 4, 5];

You can also use 'foreach' with other collection types, such as lists or dictionaries:

cs Copy Code
using System;

class Program
{
    static void Main()
    {
        List<string> names = new List<string> { "Ayan", "Suman", "Sanvi" };

        foreach (var name in names)
        {
            Console.WriteLine(name);
        }

    }
}

In this example, the 'foreach' loop iterates over each element in the names list, printing each name to the console.

Output:
Ayan
Suman
Sanvi

You can also simplify the 'IEnumerable<T>' collection list:
List<string> names = ["Ayan", "Suman", "Sanvi"];

Remember: Keep in mind that 'foreach' can be used only with collections that implement the 'IEnumerable' or 'IEnumerable<T> interface. If you need to iterate over a sequence of numbers or perform a fixed number of iterations, a traditional for loop might be more appropriate.

IEnumerable

This is a non-generic interface and it is primarily used for iterating over collections of objects without specifying the type of the elements.

Example:

cs Copy Code
using System;
using System.Collections;

class Program
{
    static void Main()
    {
        IEnumerable myEnumerable = new List<int> { 10, 20, 30, 40, 50 };
        foreach (object item in myEnumerable)
        {
            Console.Write(item + " ");
        }
    }
}
Output:
10 20 30 40 50

Note: It is part of the 'System.Collections' namespace.

IEnumerable<T>

It is an extended version of 'IEnumerable' and is used for strongly-typed collections, allowing you to specify the type of the elements in the collection.

Example:

cs Copy Code
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        IEnumerable<int> myEnumerable = new List<int> { 10, 20, 30, 40, 50 };
        foreach (int item in myEnumerable)
        {
            Console.Write(item + " ");
        }
    }
}
Output:
10 20 30 40 50

Note: It is part of the 'System.Collections.Generic' namespace.

In general, it's recommended to use 'IEnumerable<T>' when working with collections of known types, as it provides type safety and avoids the need for explicit type casting when accessing elements. 'IEnumerable' is more commonly used when dealing with non-generic collections or scenarios where the element type is not known or important.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.