Foreach Loop in C#


In C#, the foreach loop iterates collection types such as Array, ArrayList, List, Hashtable, Dictionary, etc. It can be used with any type that implements the IEnumerable interface.

Syntax:
foreach (var item in collection)
{
	//access item
																
}

The following example demonstrates iteration of an array using a foreach loop.

Example: Iterate an Array
string[] carCompanies = { "Tata Motors", "Mahindra", "Volkswagen", "Toyota" };
																
foreach(string car in carCompanies)
{
	Console.WriteLine("{0}", car);
} 
Output:
Tata Motors
Mahindra
Volkswagen
Toyota

The following example demonstrates the foreach loop on a list collection.

Example: Iterate a List
List<int> oddNumbers = new List<int>() { 1, 3, 5, 7, 9};
																
foreach(int num in oddNumbers)
{
	Console.Write(num);
}

oddNumbers.ForEach(num => Console.Write(num)); //using ForEach extension method
13579

The System.Collections.Generic namespace contains the ForEach() extension method that can be used with any built-in collection classes such as List, Dictionary, SortedList, etc.

Important Points:

  • The foreach loop iterate only in forward direction.
  • Performance wise foreach loop takes much time as compared with for loop. Because internally it uses extra memory space as well as.
  • The foreach loop use GetEnumarator() method of the IEnumerable interface. So, the foreach loop can be used with any class that has implemented the interface.
  • Exit the foreach loop by using break, return, Goto and throw.

The following example demonstrates the foreach loop on a dictionary collection.

Example: Iterate a Dictionary
var citiesOfCountry = new Dictionary<string, string>()
{
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
};
																
foreach(var city in citiesOfCountry)
{
	Console.WriteLine("{0}, {1}", city.Key, city.Value);
}
Output:
UK, London, Manchester, Birmingham
USA, Chicago, New York, Washington,
India, Mumbai, New Delhi, Pune

Implement IEnumerable Interface

As mentioned before, the foreach loop can be used to iterate any class that has implemented the IEnumerable interface. The following example demonstrates how to implement the IEnumerable interface in order to use the foreach loop with the custom class.

Example: Implement IEnumerable Interface
using System;
using System.Collections;
using System.Collections.Generic;

class Customer
{
	public int Id { get; set; }
	public string Name { get; set; }
}    
																
class Shop : IEnumerable
{
	private Customer[] custArray = new Customer[4];
																
	public Shop()
	{
		custArray[0] = new Customer() { Id = 1, Name = "Steve" };
		custArray[1] = new Customer() { Id = 2, Name = "Paul" };
		custArray[2] = new Customer() { Id = 3, Name = "Joe" };
		custArray[3] = new Customer() { Id = 4, Name = "Yash" };
	}
																
	//Here implementation for the GetEnumerator method.
	public IEnumerator GetEnumerator()
	{
		return custArray.GetEnumerator();
	}
}
																
class Program
{
	public static void Main(string[] args)
	{
		Shop objShop = new Shop();
																
		foreach (Customer cust in objShop)
		{
			Console.WriteLine(cust.Name);
		}
	}
}
Output:
Steve
Paul
Joe
Yash

Above, the Shop class has implemented the IEnumerable interface that contains the GetEnumerator() method. This will enable the Shop class to be used with the foreach loop that returns the Customer objects.