Arrays in C#

Arrays are basically a list of items of the same type that are grouped together in a single container. Unlike variables which can only contain one value at a time, arrays can contain many different values of the same type (eg. string, or integer). This tutorial explains how to create arrays, access elements in an array, and use for loops to work through the elements in arrays.

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"};
      // Create an array of int type
      int[] ages = {26,18,49,33};
      // Display second item in names array (array indexing starts at 0)
      Console.WriteLine(names[1]);
      // Display fourth item in ages array
      Console.WriteLine(ages[3]);
      // Store the names array's length (number of elements in array) in variable
      int arrayLength = names.Length;
      // Display names array's length
      Console.WriteLine(arrayLength);
      // Go through each element in names array and check if Sam exists in array
      for (int i = 0; i < arrayLength; i++) {
        if (names[i] == "Sam") {
          Console.WriteLine("Sam is here!");
        }
      }
    }
  }
}

Next tutorial: Foreach loops in C#