[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Declare and initialize empty arrays in C#

[Declare and initialize empty arrays in C#]

This is a handy trick for working with possibly empty arrays.

A C# program cannot use an array's properties and methods until the array is instantiated. For example, the following code declares an array and then tries to use its properties to loop through its values.

// Declare an array and try to use its properties. private void btnDeclare_Click(object sender, EventArgs e) { int[] values = null; try { // This fails. for (int i = 0; i < values.Length; i++) { MessageBox.Show("Value[" + i + "]: " + values[i]); } MessageBox.Show("Done"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }

The first MessageBox.Show statement fails because the array has not been created. (Note that the code sets the array variable equal to null. Otherwise the compiler correctly complains that the code is trying to use an uninitialized variable.)

You can check whether values == null to determine whether the array has been created yet, but sometimes the code would be more consistent if you could use its Length, GetLowerBound, GetUpperBound, and other members to loop over the empty array. You can do that if you initialize the array so it contains zero entries as in the following code.

int[] values = new int[0];

Now the array exists but is empty. The Length property returns 0, GetLowerBound returns 0, and GetUpperBound returns -1. The following code is similar to the previous version except it initializes the array in this way so it works.

// Declare an array and initialize it to an empty array. private void btnDeclareAndInitialize_Click(object sender, EventArgs e) { int[] values = new int[0]; try { for (int i = 0; i < values.Length; i++) { MessageBox.Show("Value[" + i + "]: " + values[i]); } MessageBox.Show("Done"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }

The moral? If you need to loop through an array whether it's empty or not, initialize it so it's empty and not just pointing to null.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.