C# cho phép multidimensional arrays (mảng nhiều chiều). Khai báo mảng 2 chiều string:
string[,] names;
Mảng 2 chiều như bảng: x hàng, y cột.
Khởi tạo multidimensional arrays bằng bracketed values cho mỗi hàng. Mảng 4 hàng, mỗi hàng 4 cột:
int[,] a = new int[4,4] {
{0, 1, 2, 3}, /* initializers for row 0 */
{4, 5, 6, 7}, /* initializers for row 1 */
{8, 9, 10, 11}, /* initializers for row 2 */
{12, 13, 14, 15} /* initializers for row 3 */
};
Ví dụ multi-dimensional arrays:
Ví dụ
using System;
namespace Program {
class Demo {
static void Main(string[] args) {
/* mảng 5 hàng 2 cột */
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8}};
int i, j;
/* xuất giá trị từng phần tử */
for (i = 0; i < 5; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
Console.ReadKey();
}
}
}
Kết quả
a[0,0] = 0
a[0,1] = 0
a[1,0] = 1
a[1,1] = 2
a[2,0] = 2
a[2,1] = 4
a[3,0] = 3
a[3,1] = 6
a[4,0] = 4
a[4,1] = 8