C#: Declaring an array

This entry is part 35 of 71 in the series C#

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];

            // 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 };

            //Declaring a string array
            string[] myString = { "One", "Two", "Three" };


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.


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