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 { int[] numbers; void SomeInitMethod() { numbers = new int[6]; } }