C# มี Collections 2 แบบ: Non-Generic (Legacy) และ Generic (Modern)
Non-Generic Collections (System.Collections)
เก็บ object → Boxing/Unboxing, No Type Safety
| Class | Description |
ArrayList | Dynamic Array of Objects |
Hashtable | Key-Value (Object-Object) |
Queue | FIFO Queue of Objects |
Stack | LIFO Stack of Objects |
SortedList | Sorted Key-Value (Object-Object) |
BitArray | Compact Bit Vector |
Generic Collections (System.Collections.Generic) — แนะนำ
Type-Safe, No Boxing, Better Performance
| Generic | Non-Generic Equivalent | Description |
List<T> | ArrayList | Dynamic Array |
Dictionary<TKey, TValue> | Hashtable | Key-Value Map |
Queue<T> | Queue | FIFO |
Stack<T> | Stack | LIFO |
SortedList<TKey, TValue> | SortedList | Sorted Key-Value |
SortedDictionary<TKey, TValue> | - | BST-based Sorted Map |
HashSet<T> | - | Unique Set (Hash) |
SortedSet<T> | - | Unique Set (Sorted) |
LinkedList<T> | - | Doubly Linked List |
ConcurrentBag<T> etc. | - | Thread-Safe Collections |
Comparison: ArrayList vs List<int>
// Non-Generic: Boxing Everywhere
ArrayList nonGeneric = new ArrayList();
nonGeneric.Add(10); // int → object (Boxing)
int val = (int)nonGeneric[0]; // Unboxing + Cast
// Generic: Type-Safe, No Boxing
List generic = new List();
generic.Add(10); // int Stays int
int val2 = generic[0]; // Direct, No Cast
Performance Impact
| Operation | ArrayList (int) | List<int> |
| Add 1M Items | ~150ms + GC Pressure | ~30ms |
| Memory | High (Boxed Objects) | Low (Contiguous Int[]) |
| Type Safety | Runtime Error | Compile Error |
Generic Methods และ Classes
// Generic Method
public T Max(T a, T b) where T : IComparable {
return a.CompareTo(b) > 0 ? a : b;
}
// Generic Class
public class Repository where T : class, new() {
public T GetById(int id) { /* ... */ }
public void Add(T entity) { /* ... */ }
}
// Usage
var repo = new Repository();
var max = Max(10, 20); // Type Inference
Constraints (where T : ...)
| Constraint | Meaning |
class | Reference Type Only |
struct | Value Type Only (Non-nullable) |
new() | Parameterless Constructor |
BaseClass | Derived from BaseClass |
Interface | Implements Interface |
notnull | Non-nullable (C# 8+) |
unmanaged | Unmanaged Type (Blittable) |
delegate / enum | Delegate / Enum Type |
สรุป
- Always Use Generic Collections — Type Safety, Performance, IntelliSense
- Non-Generics: Legacy Only (Pre-.NET 2.0), COM Interop
- เขียน Generic Classes/Methods เองได้ — Reusable, Type-Safe Algorithms
System.Collections.Immutable สำหรับ Immutable Collections
System.Collections.Concurrent สำหรับ Thread-Safe