Arrays occupy space in memory. Since they’re objects, they’re typically created with keyword new
.1 To create an array object, you specify the type and the number of array elements in an array-creation expression that uses keyword new
and returns a reference that can be stored in an array variable. The following statement creates an array object containing 12 int
elements—each initialized to 0
by default—and stores the array’s reference in variable c
:
int[] c = new int[12];
When you create an array with new
, each element of the array receives the default value for the array’s element type—0
for the numeric simple-type elements, false
for bool
elements and null
for references. The preceding statement creates the memory for the array in Fig. 8.1 but does not populate the array with the values shown in that figure. In Section 8.4.2, we’ll provide specific, nondefault initial values when we create an array.
In an array variable declaration, specifying the number of elements in the square brackets (e.g., int[12] c;
) is a syntax error.
Creating the array c
also can be performed as follows:
int[] c; // declare the array variable
c = new int[12]; // create the array; assign to array variable
In the declaration, the square brackets following int
indicate that c
will refer to an array of int
s (i.e., c
will store a reference to an array object). In the assignment statement, the array variable c
receives the reference to a new array object of 12 int
elements. The number of elements also can be specified as an expression that’s calculated at execution time.
Though arrays are fixed-length entities, you can use the static Array
method Resize
to create a new array with the specified length—class Array
defines many methods for common array manipulations. This method takes as arguments
the array to be resized and
the new length
and copies the contents of the old array into the new one, then sets the variable it receives as its first argument to reference the new array. For example, in the following statements:
int[] newArray = new int[5];
Array.Resize(ref newArray, 10);
newArray
initially refers to a five-element array. The Resize
method then sets newArray
to refer to a new 10-element array containing the original array’s element values. If the new array is smaller than the old array, any content that cannot fit into the new array is truncated without warning. The old array’s memory is reclaimed by the runtime if there are no other array variables referring to that array.2