25
© Mikael Olsson 2020
M. Olsson,
C# 8 Quick Syntax Reference,
https://doi.org/10.1007/978-1-4842-5577-3_6
CHAPTER 6
Arrays
An
array is a data structure used for storing a collection of values that all
have the same data type.
Array Declaration
To declare an array, a set of square brackets is
appended to the data type
that the array will contain, followed by the array’s name. An array can be
declared with any data type and all of its elements will then be of that type.
int[] x; // integer array
Array Allocation
The array is allocated with the new keyword, followed again by the data
type and a set of square brackets containing the length of the array. This is
the fixed number of elements that the array can contain.
Once the array is
created, the elements will automatically be assigned to the default value
for that data type, in this case, zero.
int[] x = new int[3];
26
Array Assignment
To fill the array elements, they can be referenced one at a time and then
assigned values. An array element is referenced by placing the element’s
index inside square brackets. Notice that the index for the first element
starts with zero.
x[0] = 1;
x[1] = 2;
x[2] = 3;
Alternatively, the values can be assigned all
at once by using a curly
bracket notation. The new keyword and data type may optionally be left out
if the array is declared at the same time.
int[] y = new int[] { 1, 2, 3 };
int[] z = { 1, 2, 3 };
Array Access
Once the array elements are initialized, they can be accessed by
referencing the elements’ indexes inside the square brackets.
System.Console.Write(x[0] + x[1] + x[2]); // "6"
Do'stlaringiz bilan baham: