Declaring an array

suggest change

An array can be declared and filled with the default value using square bracket ([]) initialization syntax. For example, creating an array of 10 integers:

int[] arr = new int[10];

Indices in C# are zero-based. The indices of the array above will be 0-9. For example:

int[] arr = new int[3] {7,9,4};
Console.WriteLine(arr[0]); //outputs 7
Console.WriteLine(arr[1]); //outputs 9

The index of the first element is 0. Accessing an element takes constant time: the first element costs the same as the second, the third, and so on.

You may also declare a bare reference to an array without instantiating an array.

int[] arr = null;   // OK, declares a null reference to an array.
int first = arr[0]; // Throws System.NullReferenceException because there is no actual array.

An array can also be created and initialized with custom values using collection initialization syntax:

int[] arr = new int[] { 24, 2, 13, 47, 45 };

The new int[] portion can be omitted when declaring an array variable. This is not a self-contained expression, so using it as part of a different call does not work (for that, use the version with new):

int[] arr = { 24, 2, 13, 47, 45 };  // OK
int[] arr1;
arr1 = { 24, 2, 13, 47, 45 };       // Won't compile

Implicitly typed arrays

Alternatively, in combination with the var keyword, the specific type may be omitted so that the type of the array is inferred:

// same as int[]
var arr = new [] { 1, 2, 3 };
// same as string[]
var arr = new [] { "one", "two", "three" };
// same as double[]
var arr = new [] { 1.0, 2.0, 3.0 };

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents