Sobes.tech
Junior

What types of collections exist in C#?

sobes.tech AI

Answer from AI

C# offers a variety of collection types for storing and managing data, located in different namespaces (mainly System.Collections, System.Collections.Generic, System.Collections.Concurrent, System.Collections.Immutable). They can be classified by several main features:

  1. By type of stored data:

    • Untyped: Store objects of type object (System.Collections). Require casting and may be less performant.
    • Typed (Generic): Store objects of a specific type (System.Collections.Generic). Provide type safety and better performance.
  2. By data structure:

    • Lists: Sequential collections, access elements by index.
      • ArrayList (untype)
      • List<T> (typed)
      • LinkedList<T> (typed doubly linked list)
    • Arrays: Fixed size, access by index.
      • Array (base class)
      • T[] (syntactic sugar for arrays)
    • Dictionaries: Key-value pair collections, access by key.
      • Hashtable (untype)
      • Dictionary<TKey, TValue> (typed)
      • SortedList (untype, sorted by key)
      • SortedList<TKey, TValue> (typed, sorted by key)
      • SortedDictionary<TKey, TValue> (typed, sorted by key, uses red-black tree)
    • Sets: Collections of unique elements.
      • HashSet<T> (typed, unordered)
      • SortedSet<T> (typed, ordered)
    • Queues: Collections following FIFO principle.
      • Queue (untype)
      • Queue<T> (typed)
    • Stacks: Collections following LIFO principle.
      • Stack (untype)
      • Stack<T> (typed)
  3. By thread safety:

    • Non-thread-safe: Most standard collections (System.Collections, System.Collections.Generic). Require external synchronization for multithreading.
    • Thread-safe (Concurrent): Designed for safe operation in multithreaded environments without external locking (System.Collections.Concurrent).
      • ConcurrentBag<T>
      • ConcurrentDictionary<TKey, TValue>
      • ConcurrentQueue<T>
      • ConcurrentStack<T>
  4. By mutability:

    • Mutable: Most collections allow adding, removing, and modifying elements.
    • Immutable: Ensure immutability after creation (System.Collections.Immutable). Any modification operation returns a new collection.
      • ImmutableArray<T>
      • ImmutableList<T>
      • ImmutableDictionary<TKey, TValue>
      • ImmutableHashSet<T>
      • ImmutableSortedSet<T>
      • ImmutableQueue<T>
      • ImmutableStack<T>

The choice of a specific collection type depends on the task requirements: data type, need for index or key access, element uniqueness, storage order, performance, thread safety, and mutability. The most commonly used in modern C# are the typed collections from the System.Collections.Generic namespace.