Single-Dimensional Arrays (C# Programming Guide)

You create a single-dimensional array using the new operator specifying the array element type and the number of elements. The following example declares an array of five integers:

int[] array = new int[5];

This array contains the elements from array[0] to array[4]. The elements of the array are initialized to the default value of the element type, 0 for integers.

Arrays can store any element type you specify, such as the following example that declares an array of strings:

string[] stringArray = new string[6];

Array Initialization

You can initialize the elements of an array when you declare the array. The length specifier isn't needed because it's inferred by the number of elements in the initialization list. For example:

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

The following code shows a declaration of a string array where each array element is initialized by a name of a day:

string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

You can avoid the new expression and the array type when you initialize an array upon declaration, as shown in the following code. This is called an implicitly typed array:

int[] array2 = { 1, 3, 5, 7, 9 };
string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

You can declare an array variable without creating it, but you must use the new operator when you assign a new array to this variable. For example:

int[] array3;
array3 = new int[] { 1, 3, 5, 7, 9 };   // OK
//array3 = {1, 3, 5, 7, 9};   // Error

Value Type and Reference Type Arrays

Consider the following array declaration:

SomeType[] array4 = new SomeType[10];

The result of this statement depends on whether SomeType is a value type or a reference type. If it's a value type, the statement creates an array of 10 elements, each of which has the type SomeType. If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference. In both instances, the elements are initialized to the default value for the element type. For more information about value types and reference types, see Value types and Reference types.

Retrieving data from Array

You can retrieve the data of an array by using an index. For example:

string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

Console.WriteLine(weekDays2[0]);
Console.WriteLine(weekDays2[1]);
Console.WriteLine(weekDays2[2]);
Console.WriteLine(weekDays2[3]);
Console.WriteLine(weekDays2[4]);
Console.WriteLine(weekDays2[5]);
Console.WriteLine(weekDays2[6]);

/*Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
*/

See also