</>
CompilerOnline
Open Interactive Editor

C# Collections & Generics

C# Collections

Collections provide a flexible way to work with groups of objects. Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change.

Common Collections:

  • List<T>: Standard dynamic array.
  • Dictionary<TKey, TValue>: Key-value map.
  • Queue<T> / Stack<T>: FIFO and LIFO structures.

C# collections are generic, meaning you specify the object type they hold (e.g., List<int>). This prevents boxing and unboxing overhead, enhancing performance and type-safety.

For multithreaded applications, C# provides thread-safe collections in the System.Collections.Concurrent namespace to prevent data corruption during simultaneous accesses.

C# Dictionaries

The generic Dictionary<TKey, TValue> collection manages key-value lookup pairings, guaranteeing highly efficient O(1) searches based on hash mappings.

csharp
using System;
using System.Collections.Generic;
class Program {
    static void Main() {
        var map = new Dictionary<string, int> { {"one", 1} };
        Console.WriteLine("Val: " + map["one"]);
    }
}
csharp
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<string> fruits = new List<string>() { "Apple", "Banana" };
        fruits.Add("Cherry");
        Console.WriteLine($"Total fruits: {fruits.Count}");
        Console.WriteLine($"First fruit: {fruits[0]}");
    }
}