Saturday, April 20, 2024 05:18

Table of contents >> Arrays > Declaration of arrays

Declaration of arrays

When we are dealing with declaration of an array, you should always remember that arrays in C# are fixed length. Their length is set at the time we instantiate them, it determines the total number of elements that they can store, and it cannot be changed/resized anymore. If you remember our previous lesson, we compared an array to a building, where we have apartments (array’s elements), each identified by an apartment number (index, or indices). As in real world, once a building is built after a blueprint (“instantiation” of an array – creation of a copy after the blueprint), we cannot add or remove apartments from it.

An array can be declared as follows:

In our example, we have declared an array of type integer, named myArray. Using [] we are indicating that we want to declare an array of elements, not a single element. Arrays are reference types. This means that when they are declared, they store the default value of null. This happens because the memory for the elements is not yet allocated.

Because arrays are reference types, they are initialized using the new keyword.

In the above code, we have declared an array of 6 elements length (remember, array indexes start from 0, not 1, so you access them from myArray[0] to myArray[5]!), of type integer. What this means is that the dynamic memory (also called heap) now contains 6 integer numbers, and they are all initialized with the value 0.

Always remember that declaration of arrays does not allow initialization of negative length arrays (obviously) and the type of the array must always coincide with the initialization type (we cannot write int[] myArray = new double[];).

The concepts explained in this lesson are also shown visually as part of the following video:

Tags:

Leave a Reply



Follow the white rabbit