Foreach loops in C#

This tutorial explains how to use the foreach loop to go through each element in an array. A foreach loop is simpler and easier to use than a for loop if you want to loop through each and every element in an array. Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};

      // Store length of names array in variable
      int arrayLength = names.Length;

      // Go through each name in names array and display on new line
      foreach (string name in names) {
        Console.WriteLine(name);
      }
      // Wait for user input before quitting program
      Console.ReadLine();
    }
  }
}

Next tutorial: Methods