The foreach loop in C#

Loops in C#:


Introduction :

  • There are multiple ways to writing the loops in C# the most basics loops in any programming languages are for and while loop. In C# we have another type of advance loop that is the foreach loop. We will see the syntax and execution of the foreach loop below.

  • Before we talk about the advanced foreach loop let me just give a brief explanation of the other looping condition.

Types of Loops :

LoopsWhen to use the Loop
forWe can use this loop whenever we know the starting and ending conditions.
whileWe can use this loop whenever we don't know the starting condition but we know the end condition.
do-whileWe can use this loop whenever we want to execute the loop at least one time before it checks the condition.
foreachWe can use this advanced for loop in concepts like Array and other data structure concepts where we don't want to use the index number to access the elements or Some of the data structure they don't have the index concept.

foreach loop :

  • foreach is advanced for loop which can be used to access the element of the collection without using indexes.

Syntax :

foreach(data_type var_name in collection_var) {
    //statements
}

Understanding the foreach loop :

using System;
// Topic: foreach
class MainClass {
  public static void Main (string[] args) 
  {
    int[] num = {1,2,3,4,5};
    Console.WriteLine("Using the for loop");
    //for loop
    for(int i=0;i<num.Length;i++)
    {
      Console.WriteLine(num[i]);
    }

    Console.WriteLine("Using the foreach loop");
    //foreach loop
    foreach(int a in num)
    {
      Console.WriteLine(a);
    }
  }
}

Output :

Using the for loop
1
2
3
4
5
Using the foreach loop
1
2
3
4
5

Explanation :

for loop :

  • In the above code, you can see using the for loop we need to access the elements using the index value. Here using the for loop we need to keep the index values in check that is if the index values are in the range of the given collection/array length or else this will lead to the System.IndexOutOfRangeException. And also, we need to increment/decrement the index value as per our required outputs.

foreach loop :

  • Like for loop this doesn't use any kind of index to retrieve elements from the array. This advanced foreach loop will take the array and retrieve the elements one by one until the array will not have any elements left. This happens because if the array has elements then the foreach loop returns true else it will return false and stop the execution.