C# - TPL2141 logo C# - TPL2141

foreach statement provide a simpler way to iterate over a collection of elements. It can be used with types that implement the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface. Examples of those types include:

  1. arrays
  2. List<T>
  3. Dictionary<TKey,TValue>
  4. Queue<T>
  5. SortedList<TKey,TValue>
  6. Stack<T> Class
  7. … etc

(Docs, 2018)

The structure of a foreach…in loop is as follow:

foreach (type name in collection)
{
    body
}

where

  1. type is the type of the elements inside the collection, var keyword can also be used here
  2. collection is the groups of elements to be iterated

For example, this for loop that print out all the elements in an array

int[] nums = {1, 2, 3, 45, 6, 7, 8, 9};
for (int i = 0; i < nums.Length; i++)
{
    Console.WriteLine(nums[i]);
}

can be written using foreach…in loop

int[] nums = {1, 2, 3, 45, 6, 7, 8, 9};

foreach (int num in nums)
{
    Console.WriteLine(num);
}

Live-code example

References

  1. Docs, M. (2018, June 29). foreach, in (C# reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in‘