C# foreach loop (With Example)

C# foreach loop (With Example)

In this article, how to use foreach loop in c#.

Syntax of foreach loop

foreach (element in item)
{
    // body of foreach loop
}

The foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.Generic.IEnumerable<T> or System.Collections.IEnumerable interface, as the following example:

var numbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 17 };
int count = 0;
foreach (int element in numbers )
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

Foreach loop with List (Collection)

using System;
using System.Collections.Generic;
 
namespace UsingCsharp
{
    class ForEachLoop
    {
        public static void Main(string[] args)
        {
            var numbers = new List() {1,3,2,9,6,0,5};
            int sum = 0;
 
            foreach(int number in numbers)
            {
                sum += number;
            }
            Console.WriteLine("Sum = {0}", sum);
        }
    }
}

Output

Sum = 26

Printing array using foreach loop

using System;
 
namespace Loop
{
    class ForEachLoop
    {
        public static void Main(string[] args)
        {
            char[] myArry = {'U','s','i','n','g','c','s','h','a','r','p'};
 
            foreach(char ch in myArry )
            {
                Console.WriteLine(ch);
            }
        }
    }
}

Output

U

s

i

n

g

c

s

h

a

r

p

 

2021-10-03