.NET Type System, Part II - Using Arrays
(Page 3 of 7 )
You declare an array in C# by placing empty square brackets after the type of the array, followed by the variable name that will hold the reference to the array:
int[] Numbers;
It's different from the syntax used in C++, where you put the square brackets after the variable name. Note that you need to create the array using the new operator in order to use it:
Numbers = new int[6];
This statement simply creates an array of six integers on the Managed Heap, returns the reference, and assigns it to the variable Numbers. You can declare and instantiate the array in one statement:
int[] Numbers = new int[6];
You can initialize the elements of the array within the same declaration statement:
int[] Numbers = {10,29,33,47,51,64};
You can also initialize the array after you instantiate it:
int[] Numbers = new int[6];
Numbers[0] = 10;
Numbers[1] = 29;
Numbers[2] = 33;
Numbers[3] = 47;
Numbers[4] = 51;
Numbers[5] = 64;
We initialized the array by initializing each element separately. As you can see, you access each element in the array through its index, so to access the first element of the array you write the code Numbers[0], and so on. Also note that .NET arrays are zero-based; this is an inherited feature from the base class System.Array, which you derive implicitly each time you create an array in C#.
When you declare an array of value types, the elements will contain the actual data, but when you declare an array of reference types, the array will contain references to memory addresses where the data is stored. C# provides you with single-dimension arrays, multi-dimension arrays and jagged arrays.
Next: Single-Dimension Arrays >>
More .NET Articles
More By Michael Youssef