Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Foreach in C#

C# has a specialized iteration operator called foreach.
foreach does not loop based on a boolean expression. Rather, it executes a block of code on each element in an array or other collection.

Syntax:
  1. foreach(type loopVariable in collection)
  2. {
  3. Execution steps
  4. }


In above syntax, the life of loopVariable will be only in the foreach loop.

Since the string array is a valid collection, foreach can be used to iterate through it.

Example:

  1. using System;
  2.  
  3. namespace forgetCode
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9.  
  10. string[] cityNames = { "Chennai", "Mumbai", "Bangalore", "Delhi", "Trichy" };
  11.  
  12. foreach (string name in cityNames)
  13. {
  14. Console.WriteLine(name);
  15. }
  16. }
  17.  
  18. }
  19. }


Output:

Chennai
Mumbai
Bangalore
Delhi
Trichy


..