MSDN Community

C# Collections

Welcome to the C# Collections topic on MSDN Community. This section provides comprehensive information, discussions, and resources related to data structures and collection types in the C# programming language.

Understanding C# Collections

Collections in C# are fundamental for managing groups of objects. They provide a flexible and efficient way to store, retrieve, and manipulate data. The .NET Framework offers a rich set of built-in collection classes within the System.Collections and System.Collections.Generic namespaces.

Key Collection Types

  • List<T>: A generic, dynamically sized array. It offers O(1) average time complexity for Add and Remove operations and O(1) for index access.
    List<int> numbers = new List<int>();
    numbers.Add(10);
    numbers.Add(20);
    Console.WriteLine(numbers[0]); // Output: 10
  • Dictionary<TKey, TValue>: A generic collection that stores key-value pairs. It provides O(1) average time complexity for insertions, deletions, and lookups based on the key.
    Dictionary<string, int> ages = new Dictionary<string, int>();
    ages.Add("Alice", 30);
    ages.Add("Bob", 25);
    Console.WriteLine(ages["Alice"]); // Output: 30
  • HashSet<T>: A generic collection that stores unique elements. It offers O(1) average time complexity for Add, Remove, and Contains operations.
    HashSet<string> uniqueNames = new HashSet<string>();
    uniqueNames.Add("Charlie");
    uniqueNames.Add("David");
    uniqueNames.Add("Charlie"); // Duplicate ignored
    Console.WriteLine(uniqueNames.Count); // Output: 2
  • Queue<T>: A generic collection representing a FIFO (First-In, First-Out) queue.
    Queue<string> tasks = new Queue<string>();
    tasks.Enqueue("Task 1");
    tasks.Enqueue("Task 2");
    Console.WriteLine(tasks.Dequeue()); // Output: Task 1
  • Stack<T>: A generic collection representing a LIFO (Last-In, First-Out) stack.
    Stack<int> history = new Stack<int>();
    history.Push(100);
    history.Push(200);
    Console.WriteLine(history.Pop()); // Output: 200
  • Array: The most basic collection type, fixed in size.
    int[] scores = { 95, 88, 76 };
    Console.WriteLine(scores.Length); // Output: 3

Best Practices

  • Always use generic collections (System.Collections.Generic) over non-generic ones (System.Collections) when possible to avoid boxing/unboxing and gain type safety.
  • Choose the appropriate collection type based on your performance requirements (e.g., frequent lookups vs. ordered insertion).
  • Understand the time complexity of operations for different collection types to optimize your code.

Community Resources

Engage with the C# community to ask questions, share knowledge, and find solutions: