Default Element Initialization - CSharp Language Basics

CSharp examples for Language Basics:Array

Introduction

Creating an array always preinitializes the elements with default values.

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

For example, consider creating an array of integers.

The default value for each element will be 0:

Demo Code

using System;/*from  ww w .  jav  a  2 s.  c om*/
class Test
{
   static void Main(){
      int[] a = new int[1000];
      Console.Write (a[123]);            // 0
   }
}

Result

Value types versus reference types

Whether an array element type is a value type or a reference type has important performance implications.

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

Demo Code



using System;//from w ww . j av  a  2s . c o m
     public struct Point { public int X, Y; }
class Test
{
static void Main(){
     Point[] a = new Point[1000];
     int x = a[500].X;                  // 0
     Console.WriteLine(x);

}
}

Result

Had Point been a class, creating the array would have merely allocated 1,000 null references:

Demo Code

using System;/*from w  ww  .ja  v a2 s.  c o m*/
     public class Point { public int X, Y; }
class Test
{
static void Main(){
     Point[] a = new Point[1000];
     int x = a[500].X;                  // Runtime error, NullReferenceException
Console.WriteLine(x);
}
}

Result

To avoid this error, we must explicitly instantiate 1,000 Points 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 Tutorials