foreach

An additional loop provided by C# is the foreach loop. foreach is also commonly used in many programming languages, such as Perl. Whenever it's necessary to process all values in a set one after another, foreach loops are far more comfortable than other kinds of loops.

Let's write a foreach loop and see how all values in an array can be displayed:

using System;

class   Loop
{
        public static void Main()
        {
                string[] children = { "Peter", "Paul", "Josef" };
                foreach (string child in children)
                {
                        Console.WriteLine("Child: " + child);
                }
        }
}

First, we define an array that contains the names of three children. In the next step, we process every value in the array. Every single value in the field is assigned to child and displayed on screen. This ...

Get Mono Kick Start now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.