Declare and initialize empty arrays in C#


[empty arrays]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in arrays, syntax, tips and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *