C# foreach statement

Description

The foreach statement iterates over each element in an enumerable object.

Syntax

You can get an idea of the syntax of foreach from the following code, if you assume that arrayOfInts is an array of ints:


foreach (int temp in arrayOfInts)  
{ 
    Console.WriteLine(temp);  
} 

Here, foreach steps through the array one element at a time. With each element, it places the value of the element in the int variable called temp and then performs an iteration of the loop.

Example 1

Example for foreach loop


using System;//from   w w  w  . j a va  2s .c om

class Program
{
    static void Main(string[] args)
    {
        int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        foreach (int i in intArray)
        {
            Console.WriteLine(i);
        }
    }
}

The output:

Example 2

Use break with a foreach


using System; /* w  w  w .  j  a v  a2  s. com*/
 
class MainClass { 
  public static void Main() { 
    int sum = 0; 
    int[] nums = new int[10]; 
 
    for(int i = 0; i < 10; i++)  
      nums[i] = i; 
 
    foreach(int x in nums) { 
      Console.WriteLine("Value is: " + x); 
      sum += x; 
      if(x == 4) 
         break; // stop the loop when 4 is obtained 
    } 
    Console.WriteLine("Summation of first 5 elements: " + sum); 
  } 
}

The code above generates the following result.

Example 3


using System; /*from  w  w w.ja va2s . co m*/
 
class MainClass { 
  public static void Main() { 
    int sum = 0; 
    int[,] nums = new int[3,5]; 
 
    for(int i = 0; i < 3; i++)  
      for(int j=0; j < 5; j++) 
        nums[i,j] = (i+1)*(j+1); 
 
    foreach(int x in nums) { 
      Console.WriteLine("Value is: " + x); 
      sum += x; 
    } 
    Console.WriteLine("Summation: " + sum); 
  } 
}

The code above generates the following result.

Example 4

Search an array using foreach


using System; /* w w  w.  j  a  v  a2  s .  c  om*/
 
class MainClass { 
  public static void Main() { 
    int[] nums = new int[10]; 
    int val; 
    bool found = false; 
 
    for(int i = 0; i < 10; i++)  
      nums[i] = i; 
 
    val = 5; 
 
    foreach(int x in nums) { 
      if(x == val) { 
        found = true; 
        break; 
      } 
    } 
 
    if(found)  
      Console.WriteLine("Value found!"); 
  } 
}

The code above generates the following result.

Note

You can't change the value of the item in the collection (temp in the preceding code), so code such as the following will not compile:


foreach (int temp in arrayOfInts)  
{ /*  w  ww .j  a  v  a  2s .c  om*/
  temp++; 
  Console.WriteLine(temp);  
} 

To iterate through the items in a collection and change their values, you will need to use a for loop instead.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception