You can declare an array of five integers as in the following example:
int[] myArray = new int [5];
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:
string[] myStringArray = new string[6];
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:
int[] myArray = new int[] {1, 3, 5, 7, 9};
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:
string[] weekDays = new string[] {"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};
When you initialize an array upon declaration, it is possible to use the following shortcuts:
int[] myArray = {1, 3, 5, 7, 9}; string[] weekDays = {"Sun","Sat","Mon","Tue","Wed","Thu","Fri"};
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:
int[] myArray; myArray = new int[] {1, 3, 5, 7, 9}; // OK myArray = {1, 3, 5, 7, 9}; // Error
You can pass an initialized array to a method. For example:
PrintArray(myArray);
You can also initialize and pass a new array in one step. For example:
PrintArray(new int[] {1, 3, 5, 7, 9});
In the following example, a string array is initialized and passed as a parameter to the PrintArray
method, where its elements are displayed:
// Single-dimentional arrays using System; public class ArrayClass { static void PrintArray(string[] w) { for (int i=0; i < w.Length; i++) Console.Write(w[i] + " "); } 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); } }
Sun Sat Mon Tue Wed Thu Fri
This example builds an array, myArray
, whose elements are arrays. Each one of the array elements has a different size.
// Array of arrays using System; public class ArrayTest { public static void Main() { // Declare the array of two elements: int[][] myArray = new int[2][]; // Initialize the elements: myArray[0] = new int[5] {1,3,5,7,9}; myArray[1] = new int[4] {2,4,6,8}; // Display the array elements: for (int i=0; i < 2; i++) { Console.Write("Element({0}): ", i); for (int j=0; j < myArray[i].Length; j++) Console.Write("{0} ", myArray[i][j]); Console.WriteLine(); } } }
Element(0): 1 3 5 7 9
Element(1): 2 4 6 8