All about Arrays in C#—Instantiating a One-Dimensional or Rectangular Array

Jump to: navigation, search
Visual C# Tutorials

All about Arrays in C#

© 2006 Christian Gross

Instantiating a One-Dimensional or Rectangular Array

To instantiate an array, you use an array creation expression. An array creation expression con¬sists of the new operator, followed by the base type, followed by a pair of square brackets. The length of each dimension is placed in a comma-separated list between the brackets.

The following are examples of one-dimensional array declarations:

  • Array arr2 is a one-dimensional array of four ints.
  • Array mcArr is a one-dimensional array of four MyClass references.
  • Their layouts in memory are shown in Figure 14-5.
int[]     arr2  = new int[4];
MyClass[] mcArr = new MyClass[4];
where:
no. elements = 4 (i.e. "[4]")
Array creation expression = "new MyClass[4]"

The following is an example of a rectangular array. Array arr3 is a three-dimensional array.

  • The length of the array is 3 * 6 * 2 = 36.
  • Its layout in memory is shown in Figure 14-5.
int[,,] arr3 = new int[3,6,2] ;
where:
Lengths of the dimensions = "3,6,2"

At the time of instantiation, each element is automatically initialized to the default initialization value for the type of the element.


Image:7230f1405.jpg
Figure 14-5. Declaring and instantiating arrays



Note Array creation expressions do not contain parentheses—even for reference type arrays.




prevpp.png  nextpp.png
C# Online.NET