You can declare an array of five integers as in the following example:
This array contains the elements from
myArray[0]
to myArray[4]
. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to zero.An array that stores string elements can be declared in the same way. For example:
Array Initialization
It is possible to initialize an array upon declaration, in which case, the rank specifier is not needed because it is already supplied by the number of elements in the initialization list. For example:A string array can be initialized in the same way. The following is a declaration of a string array where each array element is initialized by a name of a day:
When you initialize an array upon declaration, it is possible to use the following shortcuts:
It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable. For example:
Value Type and Reference Type Arrays
Consider the following array declaration:The result of this statement depends on whether
MyType
is a value type or a reference type. If it is a value type, the statement results in creating an array of 10 instances of the type MyType
. If MyType
is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference.For more information on value types and reference types, see Types.
Passing Arrays as Parameters
You can pass an initialized array to a method. For example:You can also initialize and pass a new array in one step. For example:
Example
In the following example, a string array is initialized and passed as a parameter to thePrintArray
method, where its elements are displayed:// cs_sd_arrays.cs using System; public class ArrayClass { static void PrintArray(string[] w) { for (int i = 0 ; i < w.Length ; i++) Console.Write(w[i] + "{0}", i < w.Length - 1 ? " " : ""); Console.WriteLine(); } public static void Main() { // Declare and initialize an array: string[] WeekDays = new string [] {"Sun","Sat","Mon","Tue","Wed","Thu","Fri"}; // Pass the array as a parameter: PrintArray(WeekDays); } }