|
Arrays in C# |
|
|
|
Arrays in C# are reference types and are very much objects in their own right. The following code shows how to declare references to an int array: int [ ] a ; // declare int array reference Here the type is int[ ] (i.e ‘reference to int array’). It is important to note here that we are not declaring the array itself but a reference to it. This merely sets aside space for reference to the array. Once we have declared the array reference, we can construct the array as follows: a = new int [ 25 ] ; // create a 25 element int array C# also uses a zero based scheme to access array elements like C, this means that the first element in the array is considered to be at 0th position. Initializing the array elements can be done as shown int [ ] odd = new int [ ] {3, 5, 7, 9 } ; The compiler works out the size for itself and we need not give it explicitly.
Multidimensional arrays are of two types – rectangular and jagged. C# has different syntax for rectangular and jagged arrays
Rectangular Arrays: In rectangular arrays every row is of same length. Following code snippet will give you an idea about rectangular arrays
using System ; static void Main ( )
}
} The output here is:
So we can see that the syntax for multidimensional arrays is a simple extension to the single dimensional case using nested curly brackets.
Jagged Arrays:
The syntax for declaring jagged arrays is different. A jagged array is an array of 1D arrays (each of which can be of different length), and this means we have to declare the jagged array itself plus each of the 1D arrays, which makes the array up. You may think of initializing the jagged array on the same lines of a rectangular array somewhat as shown below
static void Main ( string [ ] args) int [ ] [ ] odd ; Console.WriteLine ( "{0}", odd [ 0 ] [ i ] ) ; } Console.WriteLine ( "{0}", odd [ 1 ] [ j ] ) ; } }
This is because, the compiler calculates the size by looking at the no of elements in each row, but as it is not same in jagged array it flashes an error. A better and correct way to do this is as shown:
static void Main ( string [ ] args ) int [ ] [ ] odd ; // array of ( arrays ) Console.WriteLine ( "{0}", odd [ 0 ] [ i ] ) ; } Console.WriteLine ( "{0}", odd [ 1 ] [ j ] ) ; } }
even = new int [ 2 ] [ ] [ ] ; // create a 3D array
The
ways we access the two types of arrays also differ. With rectangular
array all indices are within one set of square brackets, while for a
jagged arrays each element is within its own square brackets. |