type
[*]+
array-name
=
new
type
[
dimension
+ ][*] *; |
Note: [*] is the set: [] [,] [,,] ...
|
Arrays
allow a
group of elements of a particular type to be stored in a contiguous
block of memory. Array types derive from
System.Array
and are declared in C# using left
and right
brackets ([]
). For instance:
char[] vowels = new char[] {'a','e','i','o','u'}; Console.WriteLine(vowels [1]); // Prints "e"
The preceding function call prints “e” because array
indexes start at 0. To support other languages, .NET can create
arrays based on arbitrary start indexes, but the BCL libraries always
use zero-based indexing. Once an array has been created, its length
can’t be changed. However, the
System.Collection
classes provide dynamically
sized arrays, as well as other data structures, such as associative
(key/value) arrays (see Section 3.4 in Chapter 3).
Multidimensional arrays come in two varieties, rectangular and jagged. Rectangular arrays represent an n-dimensional block; jagged arrays are arrays of arrays:
// rectangular int [,,] matrixR = new int [3, 4, 5]; // creates 1 big cube // jagged int [][][] matrixJ = new int [3][][]; for (int i = 0; i < 3; i++) { matrixJ[i] = new int [4][]; for (int j = 0; j < 4; j++) matrixJ[i][j] = new int [5]; } // assign an element matrixR [1,1,1] = matrixJ [1][1][1] = 7;
For convenience, local and field declarations can omit the array type when assigning a known value, because the type is specified in the declaration:
int[,] array = {{1,2},{3,4}};
Arrays
know their own length. For multidimensional
array methods, the array
GetLength
method returns the
number of elements for a given dimension, which is counted from
(the outermost) to the array’s Rank-1 (the innermost):
// single dimensional for(int i = 0; i < vowels.Length; i++); // multi-dimensional for(int i = 0; i < matrixR.GetLength(2); i++);
All
array indexing is bounds-checked by the
CLR, with IndexOutOf-RangeException
thrown for
invalid indexes. As in Java, bounds checking
prevents program faults and debugging difficulties while enabling
code to be executed with security restrictions.
Generally the performance hit from bounds checking is minor, and the JIT can perform optimizations such as determining each array index is safe before entering a loop, thus avoiding a check made for each iteration. In addition, C# provides unsafe code to explicitly bypass bounds checking (see Section 2.17).
3.145.111.92