ArrayList.IsFixedSize Property ตรวจสอบว่า ArrayList มีขนาดคงที่หรือไม่ (คืนค่า bool)
true= ขนาดคงที่ ไม่สามารถ Add/Remove ได้false= ขนาดเปลี่ยนแปลงได้ (ปกติ)
ตัวอย่าง
using System;
using System.Collections;
class Demo
{
public static void Main()
{
ArrayList arrList = new ArrayList();
Console.WriteLine("Adding some numbers:");
arrList.Add(45);
arrList.Add(78);
Console.WriteLine("Count: " + arrList.Count); // 2
Console.WriteLine("IsFixedSize: " + arrList.IsFixedSize); // False
}
}
ผลลัพธ์
Adding some numbers: 2 IsFixedSize: False
ทำให้ ArrayList เป็น Fixed Size
ArrayList fixedList = ArrayList.FixedSize(arrList); // fixedList.Add(100); // NotSupportedException!
ArrayList vs List<T>
| คุณสมบัติ | ArrayList | List<T> |
|---|---|---|
| Type Safety | ไม่มี (Object) | มี (Generic) |
| Performance | Boxing/Unboxing | ไม่มี Boxing |
| IsFixedSize | มี Property นี้ | ไม่มี (ใช้ AsReadOnly()) |
| สถานะ | Legacy (Non-generic) | แนะนำให้ใช้ |
List<T> ทำ Read-Only ได้อย่างไร
var list = new List<int> { 1, 2, 3 };
var readOnly = list.AsReadOnly(); // ReadOnlyCollection<int>
// readOnly.Add(4); // Compile Error