Arrays
We won’t say too much about arrays in this
chapter, because arrays are covered in detail in Chapter
5, “Arrays.” However, we’ll give you just enough
syntax here that you can code 1-dimensional arrays. Arrays in C#
are declared by fixing a set of square brackets to the end of the
variable type of the individual elements (note that all the
elements in an array must be of the same data type).
|
|
Tip |
A note to Visual Basic users: arrays in C#
use square brackets, not parentheses. C++ users will be familiar
with the square brackets but should carefully check the code
presented here because C# syntax for actually declaring array
variables is not the same as C++ syntax.
|
For example, whereas int
represents a single integer, int[]
represents an array of integers:
To initialize the array with specific dimensions,
you can use the new keyword, giving the
size in the square brackets after the type name:
All arrays are reference types and follow reference
semantics. Hence, in this code, even though the individual elements
are primitive value types, the integers
array is a reference type. So if you later write
this will simply assign the variable copy to refer to the same array - it won’t create a
new array.
To access an individual element within the array,
you use the usual syntax, placing the index of the element in
square brackets after the name of the array. All C# arrays use
zero-based indexing, so you can reference the first variable with
the index zero:
Similarly, you reference the 32 element value with
an index value of 31:
C#’s array syntax is flexible. In fact, C# allows
you to declare arrays without initializing them, so that the array
can be dynamically sized later in the program. With this technique,
you are basically creating a null
reference and later pointing that reference at a dynamically
allocated stretch of memory locations requested with the
new keyword:
You can find out how many elements are in any array
by using this syntax: