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

Generics vs Non-Generics Collections ใน C#

C# มี Collections 2 แบบ: Non-Generic (Legacy) และ Generic (Modern)

Non-Generic Collections (System.Collections)

เก็บ object → Boxing/Unboxing, No Type Safety

ClassDescription
ArrayListDynamic Array of Objects
HashtableKey-Value (Object-Object)
QueueFIFO Queue of Objects
StackLIFO Stack of Objects
SortedListSorted Key-Value (Object-Object)
BitArrayCompact Bit Vector

Generic Collections (System.Collections.Generic) — แนะนำ

Type-Safe, No Boxing, Better Performance

GenericNon-Generic EquivalentDescription
List<T>ArrayListDynamic Array
Dictionary<TKey, TValue>HashtableKey-Value Map
Queue<T>QueueFIFO
Stack<T>StackLIFO
SortedList<TKey, TValue>SortedListSorted 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

OperationArrayList (int)List<int>
Add 1M Items~150ms + GC Pressure~30ms
MemoryHigh (Boxed Objects)Low (Contiguous Int[])
Type SafetyRuntime ErrorCompile 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 : ...)

ConstraintMeaning
classReference Type Only
structValue Type Only (Non-nullable)
new()Parameterless Constructor
BaseClassDerived from BaseClass
InterfaceImplements Interface
notnullNon-nullable (C# 8+)
unmanagedUnmanaged Type (Blittable)
delegate / enumDelegate / 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