Foreach Loop in C#

Foreach loop is used enumerate or we can say iterate through list of elements, these elements can be of any type like a List of a Students.  So, you can say foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface.

You can understand foreach loop in C# looking at the below image

foreach-loop-in-csharp-min.png

the C# foreach loop starts with the foreach keyword followed by parentheses, let's understand it in detail:

  • The type is used to declare the data-type of the variable.
  • The item is the looping variable used inside the loop body into which the next element is automatically acquired from the collection on each iteration.
  • The Enumerable_collection is the array or list representing a number of values over which you want to iterate.
  • The code or statements are the block of code that executes for each iteration inside loop, for example, we are printing value using Console.WriteLine()

Let's take a look at an example, in which we will loop integer array using foreach loop

using System;
					
public class IterateUsingForeachExample
{
    public static void Main()
    {
        var numbers = new int[] { 3, 14, 15, 92, 6 };
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }       
    }
}

Output:

3
14
15
92
6

You can try it below:

Using Foreach loop in string array

Let's take a look on another example, where we will be using string array in foreach loop

using System;
					
public class Program
{
	public static void Main()
	{
		    string[] stringArray = {"Jam", "Sauce","Sugar"};

            foreach (string item in stringArray)
            {                
                Console.WriteLine(item);
            }
	}
}

Output:

Jam
Sauce
Sugar

In the above example, we are looping each string item in the stringArray, and printing it using Console.WriteLine().

Each time the loop runs, an element in the stringArray array is assigned to the variable item. For example, the first time the loop runs, the value Jam is assigned to item. It then executes the code within the block that makes up the foreach loop body. Inside body we are printing item value.

Iterate List in foreach loop

You can also loop through item of lists in C#, let's take a look on this using an example:

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
	    List<string> Vegetables = new List<string> { "Carrot", "Cucumber", "Tomato", "Onion", "Green Pepper" };
        foreach (string veg in Vegetables)
		{
          Console.WriteLine(veg);
		}
	}
}

Output:

Carrot
Cucumber
Tomato
Onion
Green Pepper

In the above example, we have declared a List of string items "Vegetables", we are then looping it using foreach loop, each item is assigned to string variable "veg" and then code inside foreach loop is executed so vegetable value is printed using "Console.WriteLine(veg)".


Share Tweet