Home Basics C# foreach statement

C# foreach statement

The foreach statement is similar to the for statement in that both allow code to iterate over the items of collections, but the foreach statement lacks an iteration index, so it works even with collections that lack indices altogether. It is written in the following form:

foreach-loop ::= “foreach” “(” variable-declaration “in” enumerable-expression “)” body
body ::= statement-or-statement-block

The enumerable-expression is an expression of a type that implements ”’IEnumerable”’, so it can be an array or a collection. The variable-declaration declares a variable that will be set to the successive elements of the enumerable-expression for each pass through the body. The foreach loop exits when there are no more elements of the enumerable-expression to assign to the variable of the variable-declaration.

Syntax

foreach (type variableName in arrayName) 
{
  // statements to be executed
}

 

Example

Lets loop through an array with some fruits

using System;

public class Program
{
	public static void Main()
	{
		string[] fruit = new string[3] { "orange", "apple", "pear" };
		foreach (string name in fruit)
		{
			Console.WriteLine(name);
		}
		Console.WriteLine("Press Enter Key to Exit..");
		Console.ReadLine();
	}
}

Run this and you should see something like this

orange
apple
pear
Press Enter Key to Exit..

list object example

Lets see how you can use a foreach loop in c# programming language to iterate or loop through list elements.

 

using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
            List fruits = new List() { "orange", "apple", "pear" };
            foreach (string fruit in fruits)
            {
                Console.WriteLine(fruit);
            }
            Console.WriteLine("Press Enter Key to Exit..");
            Console.ReadLine();
	}
}

 

You may also like