อาร์เรย์ใน C# สามารถเริ่มต้นได้หลายวิธี ให้ดูตัวอย่างด้านล่าง
วิธีที่ 1: ระบุขนาดอาร์เรย์
int[] marks = new int[5] { 99, 98, 92, 97, 95 };
วิธีที่ 2: ไม่ระบุขนาด
int[] marks = new int[] { 99, 98, 92, 97, 95 };
วิธีที่ 3: เริ่มต้นตอนประกาศ
int[] marks = { 99, 98, 92, 97, 95 };
ตัวอย่างเพิ่มเติม
using System;
namespace Demo {
class MyArray {
static void Main(string[] args) {
int[] n = new int[10];
int i, j;
for (i = 0; i < 10; i++) n[i] = i + 100;
for (j = 0; j < 10; j++) Console.WriteLine("Element[{0}] = {1}", j, n[j]);
Console.ReadKey();
}
}
}
ผลลัพธ์
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109