C# Collections Quick Reference

Note: Created for my personal use. Used Claude AI for formatting and refinement. You might not even want to read it.

1. Array Class

Type: Fixed-size, indexed, immutable length

Creation

int[] arr1 = new int[5]; …


This content originally appeared on DEV Community and was authored by RecurPixel

Note: Created for my personal use. Used Claude AI for formatting and refinement. You might not even want to read it.

1. Array Class

Type: Fixed-size, indexed, immutable length

Creation

int[] arr1 = new int[5];                    // default values
int[] arr2 = {1, 2, 3, 4, 5};              // initializer
int[] arr3 = new int[] {1, 2, 3};          // explicit

Access

  • Index: arr[0], arr[^1] (last element)
  • for loop: for(int i=0; i<arr.Length; i++)
  • foreach: foreach(int x in arr)

Add/Remove

  • ❌ Cannot add/remove (fixed size)
  • Use Array.Resize(ref arr, newSize) to create new array

Key Methods & Properties

INSTANCE (called on object: myArray.Property):

  • Length - number of elements
  • Rank - number of dimensions (1 for single-dimensional)
  • GetLength(dimension) - length of specific dimension
  • Clone() - shallow copy
  • IsFixedSize - always true
  • IsReadOnly - usually false
  • IsSynchronized - false (not thread-safe)
  • SyncRoot - object for thread synchronization

STATIC (called on type: Array.Method()):

  • Sort(array) - sorts array
  • Reverse(array) - reverses order
  • IndexOf(array, value) - find element index
  • Clear(array, index, length) - sets elements to default
  • Copy(source, dest, length) - copy elements
  • Resize(ref array, newSize) - resize array
  • Find(array, predicate) - find first match
  • FindAll(array, predicate) - find all matches
  • Exists(array, predicate) - check if any match

2. List

Type: Dynamic array, indexed, mutable, generic

Creation

List<int> list1 = new List<int>();              // empty
List<int> list2 = new List<int>(10);            // capacity
List<int> list3 = new List<int> {1, 2, 3};      // initializer
List<int> list4 = new List<int>(array);         // from collection

Access

  • Index: list[0]
  • for loop: for(int i=0; i<list.Count; i++)
  • foreach: foreach(int x in list)

Add/Remove

  • Add: Add(), AddRange(), Insert()
  • Remove: Remove(), RemoveAt(), RemoveAll(), RemoveRange(), Clear()

Key Methods & Properties

ALL INSTANCE (called on object: myList.Method()):

  • Count - number of elements
  • Capacity - allocated size
  • Add(item) - add element
  • AddRange(collection) - add multiple
  • Insert(index, item) - insert at position
  • Remove(item) - remove first occurrence
  • RemoveAt(index) - remove at index
  • RemoveAll(predicate) - remove matching
  • Clear() - remove all
  • Contains(item) - check if exists
  • IndexOf(item) - find index
  • Sort() - sort list
  • Reverse() - reverse order
  • Find(predicate) - find first match
  • FindAll(predicate) - find all matches
  • ToArray() - convert to array
  • IsReadOnly - always false

NO STATIC methods - List has only instance members

3. ArrayList

Type: Dynamic array, indexed, mutable, non-generic (stores objects)

Creation

ArrayList arr1 = new ArrayList();               // empty
ArrayList arr2 = new ArrayList(10);             // capacity
ArrayList arr3 = new ArrayList {1, "two", 3.0}; // mixed types

Access

  • Index: arr[0] (returns object, needs casting)
  • for loop: for(int i=0; i<arr.Count; i++)
  • foreach: foreach(object x in arr)

Add/Remove

  • Add: Add(), AddRange(), Insert(), InsertRange()
  • Remove: Remove(), RemoveAt(), RemoveRange(), Clear()

Key Methods & Properties

ALL INSTANCE (called on object: myArrayList.Method()):

  • Count - number of elements
  • Capacity - allocated size
  • Add(item) - add element
  • AddRange(collection) - add multiple
  • Insert(index, item) - insert at position
  • InsertRange(index, collection) - insert multiple
  • Remove(item) - remove first occurrence
  • RemoveAt(index) - remove at index
  • RemoveRange(index, count) - remove range
  • Clear() - remove all
  • Contains(item) - check if exists
  • IndexOf(item) - find index
  • Sort() - sort elements
  • Reverse() - reverse order
  • IsFixedSize - false (dynamic)
  • IsReadOnly - false
  • IsSynchronized - false (not thread-safe)
  • SyncRoot - object for thread synchronization

NO STATIC methods
⚠️ Boxing/Unboxing overhead - prefer List<T>

4. SortedList

Type: Key-value pairs, automatically sorted by key, indexed

Creation

SortedList<int, string> sl1 = new SortedList<int, string>();
SortedList<int, string> sl2 = new SortedList<int, string> 
{
    {1, "one"}, {2, "two"}
};

Access

  • By key: sl[1]
  • By index: sl.Keys[0], sl.Values[0]
  • foreach: foreach(KeyValuePair<int,string> kvp in sl)

Add/Remove

  • Add: Add(key, value), throws if key exists
  • Remove: Remove(key), RemoveAt(index), Clear()

Key Methods & Properties

ALL INSTANCE (called on object: mySortedList.Method()):

  • Count - number of pairs
  • Keys - collection of keys
  • Values - collection of values
  • Add(key, value) - add pair
  • Remove(key) - remove by key
  • RemoveAt(index) - remove by index
  • Clear() - remove all
  • ContainsKey(key) - check key exists
  • ContainsValue(value) - check value exists
  • TryGetValue(key, out value) - safe retrieval
  • IndexOfKey(key) - get index of key
  • IndexOfValue(value) - get index of value

NO STATIC methods

5. HashSet

Type: Unordered, unique elements, no indexing, fast lookups

Creation

HashSet<int> hs1 = new HashSet<int>();
HashSet<int> hs2 = new HashSet<int> {1, 2, 3};
HashSet<int> hs3 = new HashSet<int>(array);

Access

  • ❌ No index access
  • foreach only: foreach(int x in hs)
  • Use Contains() for membership test

Add/Remove

  • Add: Add() (returns false if exists), UnionWith()
  • Remove: Remove(), RemoveWhere(), Clear()

Key Methods & Properties

ALL INSTANCE (called on object: myHashSet.Method()):

  • Count - number of elements
  • Add(item) - add element (returns bool)
  • Remove(item) - remove element
  • RemoveWhere(predicate) - remove matching
  • Clear() - remove all
  • Contains(item) - O(1) lookup
  • Set operations:
    • UnionWith(other) - add all from other
    • IntersectWith(other) - keep only common
    • ExceptWith(other) - remove all in other
    • SymmetricExceptWith(other) - keep non-common
    • IsSubsetOf(other) - check subset
    • IsSupersetOf(other) - check superset
    • Overlaps(other) - check any common
    • SetEquals(other) - check same elements

NO STATIC methods

6. SortedSet

Type: Sorted order, unique elements, no indexing

Creation

SortedSet<int> ss1 = new SortedSet<int>();
SortedSet<int> ss2 = new SortedSet<int> {3, 1, 2}; // auto-sorted

Access

  • ❌ No index access
  • foreach (in sorted order): foreach(int x in ss)
  • Min, Max properties

Add/Remove

  • Add: Add() (returns false if exists)
  • Remove: Remove(), RemoveWhere(), Clear()

Key Methods & Properties

ALL INSTANCE (called on object: mySortedSet.Method()):

  • Count - number of elements
  • Min - smallest element
  • Max - largest element
  • Add(item) - add element (returns bool)
  • Remove(item) - remove element
  • RemoveWhere(predicate) - remove matching
  • Clear() - remove all
  • Contains(item) - check membership
  • Set operations: (same as HashSet)
    • UnionWith(other), IntersectWith(other), ExceptWith(other)
    • IsSubsetOf(other), IsSupersetOf(other), Overlaps(other)
  • GetViewBetween(min, max) - subset in range
  • Reverse() - iterate in reverse order

NO STATIC methods

7. Dictionary

Type: Key-value pairs, unordered, unique keys, fast lookups

Creation

Dictionary<int, string> dict1 = new Dictionary<int, string>();
Dictionary<int, string> dict2 = new Dictionary<int, string>
{
    {1, "one"}, {2, "two"}
};
// Modern syntax:
Dictionary<int, string> dict3 = new Dictionary<int, string>
{
    [1] = "one", [2] = "two"
};

Access

  • By key: dict[1] (throws if not found)
  • foreach: foreach(KeyValuePair<int,string> kvp in dict)
  • foreach keys: foreach(int key in dict.Keys)
  • foreach values: foreach(string val in dict.Values)

Add/Remove

  • Add: Add(key, value) (throws if exists), dict[key] = value (upsert)
  • Remove: Remove(key), Clear()

Key Methods & Properties

ALL INSTANCE (called on object: myDict.Method()):

  • Count - number of pairs
  • Keys - collection of keys
  • Values - collection of values
  • Add(key, value) - add pair (throws if exists)
  • Remove(key) - remove by key
  • Clear() - remove all
  • ContainsKey(key) - O(1) check
  • ContainsValue(value) - O(n) check
  • TryGetValue(key, out value) - safe retrieval
  • TryAdd(key, value) - safe add (C# 10+)

NO STATIC methods

8. SortedDictionary

Type: Key-value pairs, sorted by key, slower than Dictionary

Creation

SortedDictionary<int, string> sd1 = new SortedDictionary<int, string>();
SortedDictionary<int, string> sd2 = new SortedDictionary<int, string>
{
    {1, "one"}, {2, "two"}
};

Access

  • By key: sd[1]
  • foreach (sorted order): foreach(KeyValuePair<int,string> kvp in sd)

Add/Remove

  • Add: Add(key, value), sd[key] = value
  • Remove: Remove(key), Clear()

Key Methods & Properties

ALL INSTANCE (called on object: mySortedDict.Method()):

  • Count - number of pairs
  • Keys - sorted keys collection
  • Values - values in key order
  • Add(key, value) - add pair
  • Remove(key) - remove by key
  • Clear() - remove all
  • ContainsKey(key) - check key
  • ContainsValue(value) - check value
  • TryGetValue(key, out value) - safe retrieval

NO STATIC methods

9. Hashtable

Type: Key-value pairs, non-generic, stores objects, legacy

Creation

Hashtable ht1 = new Hashtable();
Hashtable ht2 = new Hashtable 
{
    {1, "one"}, {"key", 123}  // mixed types
};

Access

  • By key: ht[1] (returns object, needs casting)
  • foreach: foreach(DictionaryEntry de in ht)

Add/Remove

  • Add: Add(key, value), ht[key] = value
  • Remove: Remove(key), Clear()

Key Methods & Properties

  • Count - number of pairs
  • Keys - collection of keys
  • Values - collection of values
  • Contains() - check key exists
  • ContainsKey() - check key
  • ContainsValue() - check value
  • TryGetValue() - safe retrieval
  • IsFixedSize - false
  • IsReadOnly - false
  • IsSynchronized - false
  • SyncRoot - object for synchronization
  • ⚠️ Use Dictionary instead

10. Stack

Type: LIFO (Last In, First Out), no indexing

Creation

Stack<int> stack1 = new Stack<int>();
Stack<int> stack2 = new Stack<int>(array);

Access

  • ❌ No index access
  • Peek: Peek() - view top without removing
  • foreach: foreach(int x in stack) (top to bottom)

Add/Remove

  • Add: Push(item) - add to top
  • Remove: Pop() - remove and return top

Key Methods & Properties

ALL INSTANCE (called on object: myStack.Method()):

  • Count - number of elements
  • Push(item) - add to top
  • Pop() - remove and return top
  • Peek() - view top without removing
  • Contains(item) - check if exists
  • Clear() - remove all
  • ToArray() - convert to array

NO STATIC methods

11. Queue

Type: FIFO (First In, First Out), no indexing

Creation

Queue<int> queue1 = new Queue<int>();
Queue<int> queue2 = new Queue<int>(array);

Access

  • ❌ No index access
  • Peek: Peek() - view front without removing
  • foreach: foreach(int x in queue) (front to back)

Add/Remove

  • Add: Enqueue(item) - add to back
  • Remove: Dequeue() - remove from front

Key Methods & Properties

ALL INSTANCE (called on object: myQueue.Method()):

  • Count - number of elements
  • Enqueue(item) - add to back
  • Dequeue() - remove and return from front
  • Peek() - view front without removing
  • Contains(item) - check if exists
  • Clear() - remove all
  • ToArray() - convert to array

NO STATIC methods

12. LinkedList

Type: Doubly-linked list, no indexing, efficient insertion/removal

Creation

LinkedList<int> ll1 = new LinkedList<int>();
LinkedList<int> ll2 = new LinkedList<int>(array);

Access

  • ❌ No index access
  • Navigate: First, Last properties return LinkedListNode<T>
  • foreach: foreach(int x in ll)
  • Node navigation: node.Next, node.Previous

Add/Remove

  • Add:
    • AddFirst(), AddLast() - add at ends
    • AddBefore(node), AddAfter(node) - add relative to node
  • Remove:
    • Remove(value), Remove(node)
    • RemoveFirst(), RemoveLast()
    • Clear()

Key Methods & Properties

ALL INSTANCE (called on object: myLinkedList.Method()):

  • Count - number of elements
  • First - get first node (LinkedListNode)
  • Last - get last node (LinkedListNode)
  • AddFirst(value) - add at start
  • AddLast(value) - add at end
  • AddBefore(node, value) - add before node
  • AddAfter(node, value) - add after node
  • Remove(value) - remove first occurrence
  • Remove(node) - remove specific node
  • RemoveFirst() - remove from start
  • RemoveLast() - remove from end
  • Clear() - remove all
  • Find(value) - find node by value
  • Contains(value) - check if exists

Node properties (LinkedListNode):

  • Value - the data
  • Next - next node
  • Previous - previous node

NO STATIC methods

13. BitArray

Type: Array of boolean values stored as bits, mutable

Creation

BitArray ba1 = new BitArray(8);              // 8 bits, all false
BitArray ba2 = new BitArray(8, true);        // 8 bits, all true
BitArray ba3 = new BitArray(new bool[] {true, false, true});

Access

  • Index: ba[0] (returns bool)
  • for loop: for(int i=0; i<ba.Length; i++)
  • foreach: foreach(bool b in ba)

Add/Remove

  • ❌ Fixed length (use constructor for size)
  • Modify: ba[0] = true, Set(), SetAll()

Key Methods & Properties

ALL INSTANCE (called on object: myBitArray.Method()):

  • Length - number of bits
  • Count - same as Length
  • Get(index) - get bit value (bool)
  • Set(index, value) - set bit value
  • SetAll(value) - set all bits to value
  • Bitwise operations:
    • And(other) - bitwise AND
    • Or(other) - bitwise OR
    • Xor(other) - bitwise XOR
    • Not() - bitwise NOT (flip all bits)

NO STATIC methods

Quick Comparison Table

Collection Ordered Unique Indexed Add/Remove Methods Use Case
Array Yes No Yes ❌ (fixed) Fixed-size data
List Yes No Yes Add, Remove Dynamic arrays
ArrayList Yes No Yes Add, Remove Legacy (avoid)
SortedList Sorted Keys only Yes Add, Remove Small sorted key-values
HashSet No Yes No Add, Remove Unique items, fast lookup
SortedSet Sorted Yes No Add, Remove Unique + sorted
Dictionary No Keys only By key Add, Remove Fast key-value lookup
SortedDictionary Sorted Keys only By key Add, Remove Sorted key-values
Hashtable No Keys only By key Add, Remove Legacy (avoid)
Stack LIFO No No Push, Pop LIFO operations
Queue FIFO No No Enqueue, Dequeue FIFO operations
LinkedList Yes No No AddFirst/Last Frequent insert/remove
BitArray Yes No Yes Set Boolean flags

How to Identify Static vs Instance Members On-The-Fly

Visual Studio / Rider / IDE Clues

IntelliSense Icons:

  • Static members: Purple/magenta box 📦 or "S" marker
  • Instance members: Blue cube 🔷 or standard method/property icons
  • Properties: Wrench icon 🔧
  • Methods: Purple box/cube

Quick Test Method:

// Type the CLASS NAME + dot
Array.   // Shows ONLY static members

// Type your VARIABLE NAME + dot  
myArray.   // Shows ONLY instance members

Syntax Rules

Static: ClassName.Member()

Array.Sort(myArray);           // static method
Array.IndexOf(myArray, 5);     // static method
Array.Resize(ref myArray, 10); // static method

Instance: variableName.Member()

myArray.Length;      // instance property
myList.Add(10);      // instance method
myDict.Count;        // instance property

Collection-Specific Patterns

Array - THE ONLY ONE with common static methods:

  • Static: Array.Sort(), Array.Reverse(), Array.Copy(), Array.IndexOf(), Array.Clear(), Array.Resize()
  • Instance: Length, Rank, GetLength(), Clone()
  • Why? Array is a special class, methods operate on any array type

ALL Generic Collections (List<T>, Dictionary, HashSet, etc.):

  • ✅ ALL instance members only
  • ❌ NO static methods
  • Why? Modern design - everything works on the object itself

Legacy Collections (ArrayList, Hashtable):

  • ✅ ALL instance members only
  • ❌ NO static methods
  • Have extra instance properties: IsSynchronized, SyncRoot

Memory Trick: "Array is Special"

Simple Rule:

  • Array: Mix of static + instance (only collection with static methods)
  • Everything else: Instance only

Examples:

// Array - uses STATIC methods
int[] arr = {3, 1, 2};
Array.Sort(arr);              // ✓ Static
Array.Reverse(arr);           // ✓ Static
int len = arr.Length;         // ✓ Instance

// List - uses INSTANCE methods
List<int> list = new List<int> {3, 1, 2};
list.Sort();                  // ✓ Instance
list.Reverse();               // ✓ Instance
int count = list.Count;       // ✓ Instance

// Dictionary - ALL instance
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");          // ✓ Instance
dict.ContainsKey(1);         // ✓ Instance
int count = dict.Count;      // ✓ Instance

Why Array Has Static Methods?

Historical reason:

  • Array existed before generics
  • Static methods work on ALL array types: int[], string[], MyClass[]
  • Array.Sort() can sort any array without duplicating code

Modern collections:

  • Generic methods built into each class
  • list.Sort() is type-specific for List<T>
  • Cleaner design - methods belong to the object

Documentation Clue

When reading docs or hover tooltips:

// Static - shows class name in signature
public static void Sort(Array array)

// Instance - no class name, just method
public void Add(T item)

Special Properties Explained

Which Collections Have Special Properties?

Legacy/Non-Generic Collections ONLY:

  • Array - has Rank, IsFixedSize, IsReadOnly, IsSynchronized, SyncRoot
  • ArrayList - has IsFixedSize, IsReadOnly, IsSynchronized, SyncRoot
  • Hashtable - has IsFixedSize, IsReadOnly, IsSynchronized, SyncRoot
  • Queue (non-generic) - has IsSynchronized, SyncRoot
  • Stack (non-generic) - has IsSynchronized, SyncRoot

Modern/Generic Collections DO NOT have these:

  • List<T>, Dictionary<TKey,TValue>, HashSet<T>, SortedSet<T>, Queue<T>, Stack<T>, LinkedList<T> - NONE of these special properties

Why the Difference?

Legacy Collections (pre-.NET 2.0):

  • Built when multithreading was handled differently
  • Implement ICollection interface (non-generic) which requires:
    • IsSynchronized - is collection thread-safe?
    • SyncRoot - object to lock on for thread safety
    • IsFixedSize - can size change?
    • IsReadOnly - can items be modified?

Modern Generic Collections (.NET 2.0+):

  • Built with better design principles
  • Thread safety handled externally (use ConcurrentDictionary<TKey,TValue>, ConcurrentQueue<T>, etc.)
  • Don't clutter API with rarely-used properties
  • Simpler, cleaner interfaces

Property Meanings:

Rank (Array only)

  • Number of dimensions
  • int[] arr has Rank = 1
  • int[,] arr has Rank = 2
  • Use GetLength(dimension) to get size of each dimension

IsFixedSize

  • true = cannot add/remove elements (Array)
  • false = can grow/shrink (ArrayList, Hashtable)

IsReadOnly

  • true = cannot modify elements
  • Usually false for standard collections

IsSynchronized

  • true = thread-safe (rarely true by default)
  • false = NOT thread-safe (most collections)
  • Legacy property, modern code uses Concurrent* collections

SyncRoot

  • Object to use with lock() statement for thread safety
  • Modern code: use Concurrent* collections instead of locking
  • Example (legacy pattern - avoid):
lock(myArrayList.SyncRoot) 
{
    // thread-safe operations
}

Quick Rule:

  • Using generics (<T>)? No special properties.
  • Using old non-generic? Has special properties.
  • Need thread safety? Use System.Collections.Concurrent namespace (ConcurrentDictionary, ConcurrentQueue, ConcurrentBag, etc.)

Key Terminology

  • Immutable Length: Size cannot change (Array)
  • Mutable: Can add/remove elements
  • Generic: Type-safe (List, Dictionary)
  • Non-Generic: Stores objects, requires casting (ArrayList, Hashtable)
  • LIFO: Last In, First Out (Stack)
  • FIFO: First In, First Out (Queue)
  • Ordered: Maintains insertion order
  • Sorted: Automatically sorted by key/value
  • Indexed: Can access by numeric index
  • O(1): Constant time operation (very fast)
  • O(n): Linear time operation (slower with more items)


This content originally appeared on DEV Community and was authored by RecurPixel


Print Share Comment Cite Upload Translate Updates
APA

RecurPixel | Sciencx (2025-11-19T06:33:33+00:00) C# Collections Quick Reference. Retrieved from https://www.scien.cx/2025/11/19/c-collections-quick-reference/

MLA
" » C# Collections Quick Reference." RecurPixel | Sciencx - Wednesday November 19, 2025, https://www.scien.cx/2025/11/19/c-collections-quick-reference/
HARVARD
RecurPixel | Sciencx Wednesday November 19, 2025 » C# Collections Quick Reference., viewed ,<https://www.scien.cx/2025/11/19/c-collections-quick-reference/>
VANCOUVER
RecurPixel | Sciencx - » C# Collections Quick Reference. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/11/19/c-collections-quick-reference/
CHICAGO
" » C# Collections Quick Reference." RecurPixel | Sciencx - Accessed . https://www.scien.cx/2025/11/19/c-collections-quick-reference/
IEEE
" » C# Collections Quick Reference." RecurPixel | Sciencx [Online]. Available: https://www.scien.cx/2025/11/19/c-collections-quick-reference/. [Accessed: ]
rf:citation
» C# Collections Quick Reference | RecurPixel | Sciencx | https://www.scien.cx/2025/11/19/c-collections-quick-reference/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.