C# foreach statement with 3 examples

The C# foreach loop type

The foreach is used to loop through arrays or collection like lists in C#. The foreach loop is used with the in statement. This makes the process of looping through the array or collection elements simpler.

An example of foreach

You can use the for or while loop as well to iterate through elements of the collection, however, the foreach is built specifically for arrays or collections to perform the desired tasks.

You should use the foreach C# loop to get the information in arrays or collection and not to change the content to avoid unpredictable things.

Syntax of using the foreach statement

The general syntax of using the foreach statement is:

foreach (data_type identifier in expression){

// Statements to be executed



  • data_type is the type of identifier like int, string etc.
  • The identifier is the iterable variable that represents an array or collection element
  • in is a keyword used in the foreach statement
  • The expression is the array name or object collection like a list name

As we learned what is the foreach loop, now let us look at a few examples of using it.

A C# foreach example with an int array

Following is a foreach example where I used an int type array of four elements. After creating and assigning values to the array, I will use the foreach statement to display the array elements. See example by clicking the link below:

See online demo and code

A foreach example with a string array

The following example will use a string array with the foreach loop for displaying the array elements. For that, I have created an array, USStates with four State names. Then I used the foreach loop to iterate through the string array.

C# foreach loop

See online demo and code

An example of foreach with the list collection

Now let us look at an example of using a list collection with the C# foreach loop. For this example, I have created a list of four elements of int type. After creating the list, I used the foreach loop to iterate through list elements and displayed on the screen. Click the link below to see it online.

See online demo and code

You can see, the foreach loop iterates through list elements and elements are displayed on the screen.