อาร์เรย์ใช้เพื่อจัดเก็บชุดข้อมูล แต่มักจะมีประโยชน์มากกว่าที่จะคิดว่าอาร์เรย์เป็นชุดของตัวแปรประเภทเดียวกันที่จัดเก็บไว้ในตำแหน่งหน่วยความจำที่อยู่ติดกัน
อาร์เรย์หลายมิติเรียกอีกอย่างว่าอาร์เรย์สี่เหลี่ยม อาร์เรย์หลายมิติเริ่มต้นได้โดยการระบุค่าในวงเล็บสำหรับแต่ละแถว
อาร์เรย์ต่อไปนี้มี 2 แถว และแต่ละแถวมี 2 คอลัมน์
int [,] a = new int [2,2] {
{20, 50} , /* initializers for row indexed by 0 */
{15, 45} , /* initializers for row indexed by 1 */
}; เรามาดูตัวอย่างกัน −
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
/* an array with 2 rows and 2 columns*/
int [,] a = new int [2,2] {
{20, 50} , /* initializers for row indexed by 0 */
{15, 45} , /* initializers for row indexed by 1 */
};
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
Console.ReadKey();
}
}
}