#130 – Default Values of Array Elements
October 25, 2010 2 Comments
After declaring and instantiating an array, all of its elements take on default values. The default value for all numeric types is 0 and for all reference types is null. For enum types, the default value will be the element that has a value of 0–typically the first item listed in the enum.
float[] nums = new float[4]; float f1 = nums[0]; // 0.0 Cat[] pack = new Cat[5]; Cat c1 = pack[0]; // null Days[] someDays = new Days[4]; Days thatDay = someDays[2]; // Sunday (1st in list)
The same rule applies for default values in a multi-dimensional array. Each element is 0-valued or null.
int[,] nums = new int[2, 3]; int aNum = nums[1, 2]; // 0
With jagged arrays, you typically only instantiate the first dimension. Elements of that dimension are null.
int[][] jagged = new int[3][]; object o = jagged[0]; // null int n1 = jagged[0][0]; // Error: NullReferenceException jagged[0] = new int[10]; int n2 = jagged[0][2]; // 0
Days[] someDays = new Days[4];
Days thatDay = someDays[2]; // Sunday (1st in list)
Why? Where did “Sunday” get set?
It’s the default value because it’s the first enumerated value (assigned to a value of 0).