CSharp - Array Default Element Initialization

Introduction

Creating an array preinitializes the elements with default values.

The default value for a type is the result of a bitwise zeroing of memory.

TypeDefault value
All reference types null
All numeric and enum types 0
char type '\0'
bool type false

The following code creates an array of integers.

It will allocate 1,000 integers with default value 0 for each element

int[] a = new int[1000];
Console.Write (a[123]);            // 0
Console.Write (a[124]);            // 0
Console.Write (a[999]);            // 0

Value types versus reference types

When the element type is a value type, each element value is allocated as part of the array.

For example the following code defines a Point structure:

struct Point { 
        public int X, Y; 
}

When creating an array with 1000 Point structure

Point[] a = new Point[1000];
int x = a[500].X;                  // 0

Each array element is allocated memory and initialized.

If we defined Point as class, creating the array would have allocated 1,000 null references:

class Point { public int X, Y; }

Point[] a = new Point[1000];
int x = a[500].X;                  // Runtime error, NullReferenceException

To explicitly instantiate 1,000 Points class object after instantiating the array:

Point[] a = new Point[1000];
for (int i = 0; i < a.Length; i++) // Iterate i from 0 to 999
   a[i] = new Point();             // Set array element i with new point

An array itself is always a reference type object, regardless of the element type.

For instance, the following is legal:

int[] a = null;

Related Topics

Quiz