C# Language Arrays Declaring an array

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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

Which means the system starts counting the element index from 0. Moreover, accesses to elements of arrays are done in constant time. That means accessing to the first element of the array has the same cost (in time) of accessing the second element, the third element 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 };


Got any C# Language Question?