Declaring and Allocating Memory for Arrays
In C#, arrays have a fixed length that is set when they are declared and cannot be changed later. This means arrays in C# are static.
Declaring an Array
To declare an array, use the following syntax:
- The
int
keyword specifies the data type of the array elements. - The square brackets
[]
indicate thatmyArray
is an array of integers, not a single integer. - This line only creates a reference to the array on the stack. The array itself has not been created yet, and the memory required to hold the data has not been allocated. Attempting to use
myArray
at this point would result in aNullReferenceException
because no memory has been allocated for the array elements.
Note
A reference in this context is a variable that is pointing to an array object, that is an address for the start of the array object.
Allocating Memory for an Array
To allocate memory for the array, use the new
keyword:
- This statement creates six consecutive memory locations on the heap, each capable of holding an integer value.
- All elements are initialized with the default integer value of
0
.
Note
Any numeric data type will be initialised to \(0\); the bool
data type defaults to false
.
Let’s visualize what happens in memory:
Initializing an Array with Values
You can also initialize the array with specific values when declaring it:
In this case:
- The length of the array is inferred from the number of elements provided.
- The array myArray
is created with six elements, initialized to the values specified in the curly braces.
Similarly, you can create and initialize an array of strings:
Note
The curly braces {}
are used to initialize the array with values directly.
Common Mistakes to Avoid
-
Accessing Elements Before Initialization: Attempting to use an array before allocating memory with the
new
keyword will result in aNullReferenceException
. -
Changing Array Length: Once created, the length of an array cannot be changed. If you need a resizable collection, consider using a
List<T>
instead.