What is an Array

C# array stores a list of variables in the same type.

The length of an array is fixed.

Array type is declared by putting square brackets after the data type.

C# array is inherited from System.Array.

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

System.Array implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.

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

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

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

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

The following code declare an array type for int.


int[] intArray;

The size of an array is declared when allocating memory for its elements

We use the new operator to allocate memory for array.


int[] intArray = new int[100];

To reference an element from an array, we put the index inside the square bracket.


intArray[2]

The index of an array starts at 0, so the code above is referencing the third element in intArray.

The following code sets the elements in an array with index and then output them:


using System;

class Program
{
    static void Main(string[] args)
    {
        int[] intArray = new int[10];
        intArray[0] = 3;
        intArray[1] = 4;
        intArray[2] = 5;


        Console.WriteLine(intArray[0]);
        Console.WriteLine(intArray[1]);
        Console.WriteLine(intArray[2]);

    }
}

The output:


3
4
5

Single-Dimensional Arrays

You can declare a single-dimensional array of five integers as shown in the following example:


int[] array = new int[5];

This array contains the elements from array[0] to array[4].

The new operator is used to create the array and initialize the array elements to their default values.

In this example, all the array elements are initialized to zero.


class MainClass
{
    static void Main()
    {
        int[] array = new int[5];
        
        System.Console.WriteLine(array[0]);
        System.Console.WriteLine(array[1]);
        System.Console.WriteLine(array[2]);
        System.Console.WriteLine(array[3]);
        System.Console.WriteLine(array[4]);
    }
}

The following code defines an array that stores string elements.


string[] stringArray = new string[6];
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.