C Sharp

Arrays

So far, most of the examples in this tutorial have shown how to define variables in finite, predetermined numbers. However, in most practical applications, you don't know the exact number of objects you need until run time. For example, if you're developing an editor and you want to keep track of the controls that are added to a dialog box, the exact number of controls the editor will display can't be known until run time. You can, however, use an array to store and keep track of a dynamically allocated grouping of objects-the controls on the editor, in this case.

In C#, arrays are objects that have the System.Array class defined as their base class. Therefore, although the syntax of defining an array looks similar to that in C++ or Java, you're actually instantiating a .NET class, which means that every declared array has all the same members inherited from System.Array. In this section, I'll cover how to declare and instantiate arrays, how to work with the different array types, and how to iterate through the elements of an array. I'll also look at some of the more commonly used properties and methods of the System.Array class.

Declaring Arrays

Declaring an array in C# is done by placing empty square brackets between the type and the variable name, like this: -

int[] numbers;

Note that this syntax differs slightly from C++, in which the brackets are specified after the variable name. Because arrays are class-based, many of the same rules that apply to declaring a class also pertain to arrays. For example, when you declare an array, you're not actually creating that array. Just as you do with a class, you must instantiate the array before it exists in terms of having its elements allocated. In the following example, I'm declaring and instantiating an array at the same time: -

// Declares and instantiates a single-
// dimensional array of 6 integers.
int[] numbers = new int[6];

However, when declaring the array as a member of a class, you need to declare and instantiate the array in two distinct steps because you can't instantiate an object until run time: -

class YourClass
{
    image
    int[] numbers;
    image
    void SomeInitMethod()
    {
        image
        numbers = new int[6];
        image
    }
}