Posted on Updated on



  • A foreach loop is used to iterate through the items in a list. It operates on arrays or collections such as ArrayList, which can be found in the System.Collections namespace. The syntax of a foreach loop is foreach (<type> <iteration variable> in <list>) {<statements>}.
  • The type is the type of item contained in the list. For example, if the type of the list was int[] then the type would be int.
  • The iteration variable is an identifier that you choose, which could be anything but should be meaningful. For example, if the list contained an array of people’s ages, then a meaningful name for item name would be age.
  • The in keyword is required.
  • While iterating through the items of a list with a foreach loop, the list is read-only. This means that you can’t modify the iteration variable within a foreach loop. On each iteration through a foreach loop the list is queried for a new value.
  • As long as the list can return a value, this value will be put into the read-only iteration variable, causing the statements in the foreach block to be executed. When the collection has been fully traversed, control will transfer to the first executable statement following the end of the foreach block.

class ForEachLoop
{    public static void Main()                                                                        

string[] names = {“Cheryl”, “Joe”, “Matt”, “Robert”};
foreach (string person in names)

Console.WriteLine(“{0} “, person);





  • In the foreach loop, we’ve used a string variable, person, as the item name, to hold each element of the names array. As long as there are names in the array that have not been returned, the Console.WriteLine method will print each value of the person variable to the screen.

Posted by Vissicomp Technology Pvt Ltd

For more

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s