Export (0) Print
Expand All
83 out of 133 rated this helpful - Rate this topic

Multidimensional Arrays

Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns:

int[,] myArray = new int[4,2];

Also, the following declaration creates an array of three dimensions, 4, 2, and 3:

int[,,] myArray = new int [4,2,3];

Array Initialization

You can initialize the array upon declaration as shown in the following example:

int[,] myArray = new  int[,] {{1,2}, {3,4}, {5,6}, {7,8}};

You can also initialize the array without specifying the rank:

int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};

If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:

int[,] myArray;
myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};   // OK
myArray = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

You can also assign a value to an array element, for example:

myArray[2,1] = 25;

Passing Arrays as Parameters

You can pass an initialized array to a method. For example:

PrintArray(myArray);

You can also initialize and pass a new array in one step. For example:

PrintArray(new int[,] {{1,2}, {3,4}, {5,6}, {7,8}});

Example

In this example, a two-dimensional array is initialized and passed to the PrintArray method, where its elements are displayed.

// cs_td_arrays.cs
using System;
public class ArrayClass 
{
   static void PrintArray(int[,] w) 
   {
      // Display the array elements:
      for (int i=0; i < 4; i++) 
         for (int j=0; j < 2; j++)
            Console.WriteLine("Element({0},{1})={2}", i, j, w[i,j]);
   }

   public static void Main() 
   {
      // Pass the array as a parameter:
      PrintArray(new int[,] {{1,2}, {3,4}, {5,6}, {7,8}});
   }
}

Output

Element(0,0)=1
Element(0,1)=2
Element(1,0)=3
Element(1,1)=4
Element(2,0)=5
Element(2,1)=6
Element(3,0)=7
Element(3,1)=8

See Also

Arrays | Single-Dimensional Arrays | Jagged Arrays

Show:
© 2014 Microsoft. All rights reserved.