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.
- int[,] int2D = new int[4, 2];
The following code declares and creates an array of three dimensions, 4, 2, and 3 of string type.
- string[, ,] str3D = new string[4, 2, 3];
Sample Code
Create a Console application in Visual Studio, and write the below code.
- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace ConsoleDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
-
-
- int[,] _MultiDimentionArray = new int[4, 2] { { 3, 7 }, { 2, 9 }, { 0, 4 }, { 3, 1 } };
- int i, j;
-
- for (i = 0; i < 5; i++)
- {
- for (j = 0; j < 2; j++)
- {
- Console.WriteLine("a[{0},{1}] = {2}", i, j, _MultiDimentionArray[i, j]);
- }
- }
- Console.ReadKey();
- }
- }
- }
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#.