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

Happy Learning 🙂