Dark Mode
Image

C# Properties

C# Inheritance

C# Polymorphism

C# Strings

C# Generics

C# Delegates

C# Reflection

Anonymous Function

C# Multithreading

C# Synchronization

C# Web Service

C# Misc

C# New Features

C# Programs

ADO.NET Tutorial

ASP.NET Tutorial

C# Multidimensional Arrays

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 

C# Multidimensional Array Example

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

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

C# Multidimensional Array Example: Declaration and initialization at same time

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

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

We can omit the array size.

 

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

 

We can omit the new operator also.

 

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.

 

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

Comment / Reply From