BLOG.CSHARPHELPER.COM: Declare and initialize empty arrays in C#
Declare and initialize empty arrays in C#
This is a handy trick for working with arrays that may be empty.
A C# program cannot use an array's properties and methods until the array is instantiated. For example, the following code declares an array. 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.)
// 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); } }
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 Length, GetLowerBound, GetUpperBound, and other array properties 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. Length returns 0, GetLowerBound returns 0, and GetUpperBound returns -1. The following code is similar to the previous versoin 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); } }
Comments