ArrayList เป็น Legacy Non-generic Collection (ใช้ Object) แปลงเป็น Typed Array ด้วย ToArray(Type)
ตัวอย่างพื้นฐาน
using System;
using System.Collections;
public class Program
{
public static void Main()
{
ArrayList arrList = new ArrayList();
arrList.Add("one");
arrList.Add("two");
arrList.Add("three");
// ToArray(Type) - ต้องระบุ Type
string[] arr = arrList.ToArray(typeof(string)) as string[];
foreach (string s in arr)
Console.WriteLine(s);
}
}
ผลลัพธ์
one
two
three
วิธีที่ดีกว่า: ใช้ List<T> แทน ArrayList (Generic)
// Modern C# - ใช้ List แทน ArrayList
var list = new List { "one", "two", "three" };
// ToArray() - ไม่ต้องระบุ Type, Type-Safe
string[] arr = list.ToArray();
// หรือ ToArray แบบ Implicit
var arr2 = list.ToArray(); // string[]
ArrayList ToArray Overloads
// 1. ToArray() - คืน Object[] (Non-generic)
object[] objArray = arrList.ToArray();
// 2. ToArray(Type) - คืน Typed Array (ต้อง Cast)
string[] strArray = (string[])arrList.ToArray(typeof(string));
// หรือ
string[] strArray2 = arrList.ToArray(typeof(string)) as string[];
ArrayList to List<T> (แปลงเป็น Generic List)
// Cast แล้ว ToList
var list = arrList.Cast().ToList();
// หรือ Manual
var list = new List();
foreach (object obj in arrList)
list.Add((string)obj);
Multidimensional / Nested Collections
// ArrayList ของ ArrayList
var jagged = new ArrayList
{
new ArrayList { 1, 2 },
new ArrayList { 3, 4, 5 }
};
// Flatten
var flat = jagged.Cast()
.SelectMany(al => al.Cast())
.ToArray(); // int[] {1,2,3,4,5}
Performance Notes
ArrayListเก็บเป็น `object[]` → Boxing/Unboxing สำหรับ Value TypesList<T>เก็บเป็น `T[]` → No Boxing, Type-Safe, FasterToArray()สร้าง Array ใหม่ (Copy) - O(N) Time & Space
เมื่อไหร่ยังใช้ ArrayList
- Legacy Code (.NET 1.x/2.0)
- COM Interop
- Mixed Types จริงๆ (Rare - ใช้ `List
- Reflection/Serialization ที่ต้องการ Non-generic
สรุปแนะนำ
// ✅ Modern Way
List list = new List { "a", "b", "c" };
string[] array = list.ToArray();
// ❌ Legacy Way
ArrayList arrList = new ArrayList { "a", "b", "c" };
string[] array = (string[])arrList.ToArray(typeof(string));