C#: Declaring an array

Array is for storing multiple variables of the same type in an array data structure.

As in any other programming languages such as C++, C# arrays are zero indexed; that is, the array indexes start at zero.

When declaring an array, the square brackets [] must come after the type such as

int[] array1
Array Declaration
using System;

namespace MyArray
{
    class Program
    {
        static void Main()
        {
            // Declare a single-dimensional array, values will be initialize to 0  
            int[] array1 = new int[5];
            Console.WriteLine(array1[0]); 

            // Declare and set array element values 
            int[] array2 = new int[] { 1, 3, 5, 7, 9 };
            Console.WriteLine(array2[0]);

            // Alternative syntax 
            int[] array3 = { 1, 2, 3, 4, 5, 6 };
            Console.WriteLine(array3[5]);

            //Declaring a string array
            string[] myString = { "One", "Two", "Three" };
            Console.WriteLine(myString[1]);

            Console.ReadLine();
        }
    }
}

The outputs from running the above code will be 0, 1, 6, Two.

When declaring an array without initial values

int[] array1 = new int[5];

Values will be initialize to 0.

C# supports single-dimensional, multidimensional, and array-of-arrays (jagged arrays).

For now, we only look at single-dimensional arrays.

array

Series Navigation<< C#: Main method and its arguments args
C#: Using for loop to find array total >>