An array is a group of values that belong to same data type. The values in an array are called as ‘elements’. The following code snippet shows how to declare and initialize an array.
int[] intArray = new int[3]; //New array with 3 integer elements
//Array initialization at the time of declaration
int[] intArray1 = new int[3] { 10, 20, 30 };
//Array size is determined by number of values in the initilization
int[] intArray2 = new int[] { 20, 30, 40 };
//Arrady initialization without “new” operator
int[] intArray3 = {30,40,50};
//string array
string[] stringArray = new string[] { “one”, “two”, “three” };
To store a value into the second element of the array:
intArray[3] = 25;
To retrieve value of first element in the array:
Console.WriteLine(“First element: {0}”, stringArray[0]);
The examples shown above deal with single dimensional arrays. You can store large number of values with multi-dimensional arrays. Here are some examples.
int[,] intArray = new int[2,2]; //New array with total 4 integer elements
int[,] intArray1 = new int[2,2] { {10, 20}, {30,40} };
int[,] intArray2 = new int[,] { { 10, 20 }, { 30, 40 } };
int[,] intArray3 = { { 10, 20 }, { 30, 40 } };
string[,] stringArray = new string[,] { {“one”, “two”}, {“three”, “four”} };
Lastly, you can declare an array of arrays. Here is how:
int[][] intArray = new int[2][];
intArray[0] = new int[2];
intArray[1] = new int[3];
(or)
int[][] intArray1 = new int[2][] { new int[]{10,20}, new int[]{30,40,50}};
By
Team CVK (Microsoft Competency)