Control Flow

For Each in C#

To use a control structure that executes a block of code a specified number of times, used primarily for arrays.


Syntax
foreach (dataType valueName in arrayName) { 
   //statements 
}

Notes

Same as the for loop with different formatting and used for arrays.

dataType is the type of the valueName. valueName is defined element name for the array (arrayName). 'in' is used to associate each element with the array.

Foreach goes through the elements of the array in order.


Example
string[] workDays = {"Monday","Tuesday", "Wednesday"};

foreach (string day in workDays) { 
   Console.WriteLine(day); 
}

Add to Slack

< For Loop   |   While Loop >

© 2019 SyntaxDB. All Rights Reserved.