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

การเพิ่ม Item เข้า ArrayList ใน C#

ArrayList เป็น Non-generic Collection ใน System.Collections ปรับขนาดได้อัตโนมัติ (Dynamic Resize) แต่ ไม่แนะนำสำหรับโค้ดใหม่ — ควรใช้ List<T> แทน

เหตุผลไม่ควรใช้ ArrayList

  • ❌ Boxing/Unboxing: เก็บ object → Value Types (int, struct) ถูก Box ทุกครั้ง
  • ❌ No Type Safety: ใส่ได้ทุก Type — Error พบได้ตอน Runtime เท่านั้น
  • ❌ Performance: ช้ากว่า List<T> มาก
  • ✅ ใช้ได้เฉพาะ: Legacy Code, COM Interop, หรือ Framework ที่บังคับ

การใช้งาน ArrayList (เพื่อความเข้าใจ Legacy Code)

สร้างและเพิ่ม Item

using System.Collections;

ArrayList list = new ArrayList();
list.Add(30);        // int → Boxed
list.Add("Hello");   // string (Reference Type)
list.Add(3.14);      // double → Boxed

เพิ่มหลาย Item (AddRange)

ArrayList list1 = new ArrayList { 30, 70 };
ArrayList list2 = new ArrayList { 200, 240 };
list1.AddRange(list2); // list1 = {30, 70, 200, 240}

เข้าถึงและ Cast

int first = (int)list1[0]; // ต้อง Cast กลับ (Unboxing)
string second = (string)list1[1];

ตัวอย่างครบถ้วน (Legacy Style)

using System;
using System.Collections;

public class MyClass {
    public static void Main() {
        ArrayList arr1 = new ArrayList();
        arr1.Add(30);
        arr1.Add(70);
        
        ArrayList arr2 = new ArrayList();
        arr2.Add(200);
        arr2.Add(240);
        
        arr1.AddRange(arr2);
        
        for (int i = 0; i < arr1.Count; i++) {
            Console.WriteLine(arr1[i]); // Boxing/Unboxing ทุกครั้ง
        }
    }
}

Modern Alternative: List<T>

using System.Collections.Generic;

var list = new List(); // Type-Safe, No Boxing
list.Add(30);
list.Add(70);
list.AddRange(new[] { 200, 240 });

foreach (int item in list) { // No Cast, No Boxing
    Console.WriteLine(item);
}

Comparison Table

FeatureArrayListList<T>
Type Safety❌ Object-based✅ Generic
Boxing (Value Types)✅ Yes (Slow)❌ No (Fast)
Compile-time Checking❌ No✅ Yes
PerformanceSlowFast
LINQ SupportLimited (Cast needed)Full

สรุป

อย่าใช้ ArrayList ในโค้ดใหม่ ใช้ List<T> แทนเสมอ ArrayList เหลืออยู่เพื่อ Backward Compatibility เท่านั้น