Arrays
Arrays allow a group of elements of a particular type to be stored in a contiguous block of memory. An array is specified by placing square brackets after the element type. For example:
int[] nums = new int[2];
nums[0] = 100;
nums[1] = 200;
char[ ] vowels = new char[ ] {'a','e','i','o','u'};
Console.WriteLine(vowels [1]); // Prints "e"That last line prints "e" because array indexes
start at 0. To support other languages, .NET can create arrays based
on arbitrary start indexes, but all the libraries use zero-based
indexing. Once an array is created, its length cannot be changed.
However, the
System.Collection
classes provide dynamically sized
arrays, as well as other data structures, such as associative
(key/value) arrays.
Multidimensional Arrays
Multidimensional arrays come in two
varieties: rectangular and jagged. Rectangular arrays represent an
n-dimensional block, while jagged arrays are
arrays of arrays. In this example we make use of the
for loop, which is explained later in Section 1.8. The
for loops here simply iterate through each item in
the 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;Local Field Array Declarations
For convenience, local and field declarations may omit the array type when assigning ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access