[Previous] [Contents] [Next]

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
    }
}

[Previous] [Contents] [Next]