Multi Dimensional Array In C# With Example

In this article, I will discuss multi-dimensional array in C# with an example. A multi-dimensional array in C# is an array that contains more than one rows to store the data.
 
Here are some facts about multi-dimensional arrays: 
  • Multi-dimensional arrays are also known as rectangular arrays in C#
  • Each row in the array has same number of elements (length). 
  • A multi-dimensional array can be a 2-d (two-dimensional) array or a 3-D (three-dimensional) array or even more, an n-dimensional array.
Arrays are categorized into the following three categories. 
  • Single dimensional
  • Multi-dimentional
  • Jagged
The following code snippet declares a two-dimensional array of four rows and two columns of int type. This array can store int values only.
  1. int[,] int2D = new int[4, 2];  
The following code declares and creates an array of three dimensions, 4, 2, and 3 of string type.
  1. string[, ,] str3D = new string[4, 2, 3];  
Sample Code
 
Create a Console application in Visual Studio, and write the below code. 
  1. using System;  
  2.  using System.Collections;  
  3.  using System.Collections.Generic;  
  4.     namespace ConsoleDemo  
  5.     {  
  6.         class Program  
  7.         {  
  8.             static void Main(string[] args)  
  9.             {  
  10.                 //Multi-Dimensional array Example  
  11.                 /* Array with 4 rows and 2 columns*/  
  12.                 int[,] _MultiDimentionArray = new int[4, 2] { { 3, 7 }, { 2, 9 }, { 0, 4 }, { 3, 1 } };  
  13.                 int i, j;  
  14.                  
  15.                 for (i = 0; i < 5; i++)  
  16.                 {  
  17.                     for (j = 0; j < 2; j++)  
  18.                     {  
  19.                         Console.WriteLine("a[{0},{1}] = {2}", i, j,  _MultiDimentionArray[i, j]);  
  20.                     }  
  21.                 }  
  22.                 Console.ReadKey();  
  23.             }  
  24.         }      
  25.     } 
In this above code, a 4x2 multi-dimensional array is initialized with values in it.
 
I hope you understood the concept of multi-dimensional arrays in C#.
 
Here is a detailed tutorial on Working With Arrays In C#.