Note : This post is first published on June-2015 in my previous blog Techkindle. Moving the content here.

foreach:

It repeats a group of embedded statements for each element in an array or an object collection. By a collection, we mean any class, struct, or interface that implements the IEnumerable interface.
foreach gives read-only access to the array contents, so we can not change the values of any of the elements.
Only forward iteration is possible in for-each loop.
The condition to work with IEnumerable objects is that the underlying collection must not change while you are accessing it. You can presume that the Enumerable object is a snap shot of the original collection, so if you tries to change the collection while enumerating, it will throw an exception. However the fetched objects in Enumeration is not immutable at all.
Since the variable used in foreach loop is local to the loop block this variable is however not available outside the block.

In the below code we can observe the following points,

  • If we try to modify the foreach iteration variable either primitive type (int) or a user defined class (Customer), we get compile time error.
  • If we try to add/remove any item from the collection, we get run time exception.
  • We can always modify the object properties(Name property in Customer type), which are not immutable.

Sample Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForeachTest
{
public class Program
{
static void Main(string[] args)
{
List<int> lstValues = new List<int> { 1, 2, 3, 4, 5 };
foreach (int value in lstValues)
{
value = 2;//Compiler error, cannot assign to foreach iteration variable.
}
List<Customer> lstCustomer = new List<Customer>
{
new Customer("Steve"),
new Customer("Kevin"),
new Customer("Cook"),
new Customer("Finn"),
};
foreach (Customer objCustomer in lstCustomer)
{
Console.WriteLine(objCustomer.ToString());
objCustomer.Name = "Rohit"; //This is ok, objects is mutable.
objCustomer = null;//Compiler error, "cannot assign to foreach iteration variable."
lstCustomer.Remove(objCustomer);//Runtime exception, "Collection was modified; enumeration operation may not execute."
}
Console.ReadKey();
}
}
public class Customer
{
public string Name { get; set; }
public Customer(string name)
{
this.Name = name;
}
public override string ToString()
{
return Name;
}
}
}

view raw
foreachtest
hosted with ❤ by GitHub

Happy Learning 🙂