ประกาศ Array ใน C#:
int[] runs = new int[10]; // ประกาศขนาด 10
ประกาศและกำหนดค่าเริ่มต้นในบรรทัดเดียว:
int[] runs = new int[5] {99, 92, 95, 0, 0};
หรือย่อได้เป็น:
int[] runs = {99, 92, 95};
โค้ดตัวอย่างเต็ม
using System;
namespace Program
{
class Demo
{
static void Main(string[] args)
{
int[] runs = new int[3] {149, 123, 257};
int j;
for (j = 0; j < 3; j++)
{
Console.WriteLine("Score of Cricketer[{0}] = {1}", j, runs[j]);
}
Console.ReadKey();
}
}
}
ผลลัพธ์
Score of Cricketer[0] = 149 Score of Cricketer[1] = 123 Score of Cricketer[2] = 257
คุณสมบัติสำคัญ
- Array ใน C# เป็น Reference Type
- ดัชนีเริ่มจาก 0 (Zero-based)
- ขนาดคงที่หลังสร้าง (Fixed size)
- ใช้
LengthProperty ดูขนาด