The foreach loop enables you to iterate through each item in a collection. A collection type could be the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface.
using System;
using System.Collections.Generic;
IList<int> intArr = new List<int>() { 1, 2, 3, 4, 5 };
foreach (var item in intArr)
{
Console.Write($" {item} ");
}
Console.WriteLine();
Output:
1 2 3 4 5
Key Point
You can’t change the value of the item in the collection within foreach. for example:
foreach (var item in intArr)
{
Console.Write($" {item} ");
item += 10;
}
You will get compile error:
error CS1656: Cannot assign to 'item' because it is a 'foreach iteration variable'
If you do want to change the value, you can use for loop instead.
using System;
using System.Collections.Generic;
IList<int> intArr = new List<int>() { 1, 2, 3, 4, 5 };
for (int i = 0; i < intArr.Count; i++)
{
intArr[i] += 10;
}
foreach (var item in intArr)
{
Console.Write($" {item} ");
}
Console.WriteLine();
Output:
11 12 13 14 15