Array = Fixed-size, Contiguous Memory
List<T> = Dynamic Array (Wrapper ของ Array) — Resize ได้อัตโนมัติ
Array (T[])
// Declaration
int[] arr = new int[5]; // Size 5, Zero-initialized
int[] arr2 = new int[5] { 23, 14, 11, 78, 56 }; // Init with Values
int[] arr3 = { 23, 14, 11, 78, 56 }; // Implicit Size
// Access
arr[0] = 100;
int val = arr[2];
// Fixed Size — Cannot Add/Remove
// arr.Add(10); // ❌ No Add Method
List<T>
using System.Collections.Generic;
var list = new List();
list.Add("Audi");
list.Add("BMW");
list.Add("Chevrolet");
list.Add("Hyundai");
// Access
list[0] = "Tesla"; // Indexer
string first = list[0];
// Dynamic Operations
list.Insert(1, "Ford"); // Insert at Index
list.Remove("BMW"); // Remove by Value
list.RemoveAt(2); // Remove by Index
list.AddRange(new[] { "VW", "Volvo" });
// Capacity vs Count
Console.WriteLine($"Count: {list.Count}, Capacity: {list.Capacity}");
Comparison
| Feature | Array (T[]) | List<T> |
|---|---|---|
| Size | Fixed | Dynamic (Auto-resize) |
| Add/Remove | ❌ | ✅ Add, Insert, Remove, RemoveAt, Clear |
| Memory | Contiguous, Exact Size | Contiguous, Capacity ≥ Count (Over-allocates) |
| Performance (Index) | Fastest (Direct) | Fast (Bounds Check + 1 Indirection) |
| Performance (Add) | N/A | Amortized O(1), Occasional O(n) Resize |
| LINQ | ✅ (AsEnumerable) | ✅ Native |
| Interfaces | IList<T>, IReadOnlyList<T> | IList<T>, ICollection<T>, IEnumerable<T> |
| Span Support | ✅ arr.AsSpan() | ✅ CollectionsMarshal.AsSpan(list) (.NET 5+) |
Internal: List<T> Resizing
// Simplified Internal Logic
private T[] _items;
private int _size;
public void Add(T item) {
if (_size == _items.Length) {
// Resize: Double Capacity (or 4 if empty)
int newCapacity = _items.Length == 0 ? 4 : _items.Length * 2;
Array.Resize(ref _items, newCapacity);
}
_items[_size++] = item;
}
เมื่อไหร่ใช้ไหน?
- Array: ขนาดทราบล่วงหน้า, Performance Critical, Interop, Stackalloc, Numeric Computing
- List<T>: ขนาดไม่ทราบ, ต้อง Add/Remove บ่อย, General Purpose Collection
- ImmutableArray<T> /
IReadOnlyList<T>: Read-only View, Thread Safety
Conversion
// List → Array
int[] array = list.ToArray();
// Array → List
List list = new List(array);
// หรือ
List list = array.ToList(); // ต้อง using System.Linq
สรุป
ส่วนใหญ่ใช้ List<T> ไปเลย — สะดวก ปลอดภัย เร็วพอ ใช้ Array เฉพาะเมื่อมีเหตุผลชัดเจน (Performance, Interop, Fixed Size)