C# foreach Loop: Use, Syntax, and Examples

In this tutorial, we will learn about the foreach loop in C# with its use, syntax, and examples. By IncludeHelp Last updated : April 07, 2023

C# foreach Loop

The foreach is a special type of loop used in C#, which is used to access the elements of an array or collection, according to its name, it can access each element of an array or collection.

Syntax

foreach (var item in collection){
	//Statements               
}

Consider the below code snippet:

foreach (int X in ARR){
	Console.Write(X+ " ";);                
}

Here, ARR is an array of elements and X is integer variables it accesses each element of array one by one and prints them with the help of foreach loop.

Example 1: foreach Loop with Integer Array

using System;

namespace arrayEx {
  class Program {
    static void Main(string[] args) {
      int[] ARR = {1, 2, 3, 4, 5};

      Console.WriteLine("Elements are:");
      foreach(int X in ARR) {
        Console.Write(X + " ");
      }
      Console.WriteLine();
    }
  }
}

Output

Elements are:
1 2 3 4 5
Press any key to continue . . .

Example 2: foreach Loop with Character Array

using System;

namespace Loop {
  class Program {
    public static void Main(string[] args) {
      char[] charArray = {'I', 'N', 'D', 'I', 'A'};

      foreach(char ch in charArray) {
        Console.WriteLine(ch);
      }
    }
  }
}

Output

I
N
D
I
A

Example 3: foreach Loop with List Collection

using System;
using System.Collections.Generic;

namespace ForEachLoop {
  class Program {
    public static void Main(string[] args) {
      var intList = new List < int > () {10, 20, 30, 40, 50};
      int sumElements = 0;
      
      foreach(int n in intList) {
        sumElements += n;
      }
      
      Console.WriteLine("Sum of all elements = {0}", sumElements);
      Console.ReadLine();
    }
  }
}

Output

Sum of all elements = 150



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.