Home > Articles

Introducing C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 leads to the following result:

[hs@duron mono]$ mono children.exe
Child: Peter
Child: Paul
Child: Josef

This way, it's truly simple to implement dynamic data structures for storing an undefined amount of data.

  • + Share This
  • 🔖 Save To Your Account