C# Multidimensional Arrays

The multidimensional array is also known as rectangular arrays in C#. It can be two dimensional or three dimensional. The data is stored in tabular form (row * column) which is also known as matrix.

To create multidimensional array, we need to use comma inside the square brackets. For example:

int[,] arr=new int[3,3];//declaration of 2D array
        int[,,] arr=new int[3,3,3];//declaration of 3D array
Example

Let's see a simple example of multidimensional array in C# which declares, initializes and traverse two dimensional array.

snippet
using System;
public class MultiArrayExample
{
    public static void Main(string[] args)
    {
        int[,] arr=new int[3,3];//declaration of 2D array
        arr[0,1]=10;//initialization
        arr[1,2]=20;
        arr[2,0]=30;

        //traversal
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                Console.Write(arr[i,j]+" ");
            }
            Console.WriteLine();//new line at each row
        }
    }
}
Output
0 10 0 0 0 20 30 0 0

Declaration and initialization at same time

There are 3 ways to initialize multidimensional array in C# while declaration.

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

We can omit the array size.

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

We can omit the new operator also.

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

Let's see a simple example of multidimensional array which initializes array at the time of declaration.

Example
snippet
using System;
public class MultiArrayExample
{
    public static void Main(string[] args)
    {
        int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//declaration and initialization

        //traversal
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                Console.Write(arr[i,j]+" ");
            }
            Console.WriteLine();//new line at each row
        }
    }
}
Output
1 2 3 4 5 6 7 8 9
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +