Arrays (C# Programming Guide)

An array is a data structure that contains several variables of the same type. Arrays are declared with a type:

type[] arrayName;

The following examples create single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass
{
    static void Main()
    {
        // Declare a single-dimensional array  
        int[] array1 = new int[5];

        // Declare and set array element values 
        int[] array2 = new int[] { 1, 3, 5, 7, 9 };

        // Alternative syntax 
        int[] array3 = { 1, 2, 3, 4, 5, 6 };

        // Declare a two dimensional array 
        int[,] multiDimensionalArray1 = new int[2, 3];

        // Declare and set array element values 
        int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };

        // Declare a jagged array 
        int[][] jaggedArray = new int[6][];

        // Set the values of the first array in the jagged array structure
        jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
    }
}

Array Overview

An array has the following properties:

  • An array can be Single-Dimensional, Multidimensional or Jagged.

  • The default value of numeric array elements are set to zero, and reference elements are set to null.

  • A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

  • Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.

  • Array elements can be of any type, including an array type.

  • Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.8 Arrays

  • 12 Arrays

See Also

Concepts

C# Programming Guide

Array Collection Type

Arrays in the Common Type System

Reference

Collection Classes (C# Programming Guide)

Array Usage Guidelines