Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

อาร์เรย์ใน C# เริ่มจากดัชนี 0 (Zero-Indexed) ไหม?

คำตอบ: ใช่ อาร์เรย์ใน C# เริ่มจากดัชนี 0 (Zero-Indexed)

ใน C# อาร์เรย์ทุกประเภทใช้ดัชนีเริ่มจาก 0 เสมอ ซึ่งเป็นมาตรฐานของภาษาโปรแกรมมิ่งสมัยใหม่ส่วนใหญ่ (C, C++, Java, JavaScript, Python ฯลฯ)

การทำงานของดัชนี (Index)

จำนวนสมาชิก ดัชนี (Indexes) ความยาว (Length)
0 (ว่างเปล่า) ไม่มี 0
1 0 1
2 0, 1 2
3 0, 1, 2 3
5 0, 1, 2, 3, 4 5

สูตรทั่วไป: ดัชนีสุดท้าย = Length - 1

ตัวอย่างการประกาศและใช้งานอาร์เรย์

/* เริ่มจากดัชนี 0 */
for (int i = 0; i < 5; i++)
{
    n[i] = i + 5;
}

ตัวอย่างโค้ดสมบูรณ์

using System;

namespace ArrayApplication
{
    class MyArray
    {
        static void Main(string[] args)
        {
            int[] n = new int[5]; // สร้างอาร์เรย์ขนาด 5 (ดัชนี 0-4)
            int i, j;
            
            /* เริ่มจากดัชนี 0 */
            for (i = 0; i < 5; i++)
            {
                n[i] = i + 5;
            }
            
            for (j = 0; j < 5; j++)
            {
                Console.WriteLine("Element[{0}] = {1}", j, n[j]);
            }
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Element[0] = 5
Element[1] = 6
Element[2] = 7
Element[3] = 8
Element[4] = 9

ข้อผิดพลาดที่พบบ่อย (Off-by-one Error)

// ❌ ผิด - เข้าถึงเกินขอบเขต
for (int i = 0; i <= 5; i++)  // i จะเป็น 5 ซึ่งเกิน Length (0-4)
{
    Console.WriteLine(n[i]); // IndexOutOfRangeException!
}

// ✅ ถูกต้อง
for (int i = 0; i < 5; i++)  // i < Length
{
    Console.WriteLine(n[i]);
}

// ✅ ถูกต้อง - ใช้ Length property
for (int i = 0; i < n.Length; i++)
{
    Console.WriteLine(n[i]);
}

// ✅ ทันสมัย - ใช้ foreach (ไม่ต้องกังวลดัชนี)
foreach (int value in n)
{
    Console.WriteLine(value);
}

หลายมิติ (Multidimensional Arrays)

อาร์เรย์หลายมิติก็ใช้ zero-indexed เช่นกัน

// 2 มิติ: 3 แถว x 4 คอลัมน์
int[,] matrix = new int[3, 4];

// ดัชนีแถว: 0, 1, 2
// ดัชนีคอลัมน์: 0, 1, 2, 3
matrix[0, 0] = 1; // แถวแรก คอลัมน์แรก
matrix[2, 3] = 99; // แถวสุดท้าย คอลัมน์สุดท้าย

สรุป

  • ✅ อาร์เรย์ C# เริ่มจากดัชนี 0 เสมอ
  • ✅ ดัชนีสุดท้าย = Length - 1
  • ✅ ใช้ array.Length หรือ foreach เพื่อหลีกเลี่ยงข้อผิดพลาด
  • ✅ ใช้ได้กับอาร์เรย์ทุกประเภท (1D, 2D, Jagged arrays)