CSharp examples for Language Basics:Array
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:
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 } }
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:
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); } }
Had Point been a class, creating the array would have merely allocated 1,000 null references:
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); } }
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;