C# Collections

This section covers the various collection types available in C# and the .NET Framework, providing efficient ways to store and manage groups of objects.

Overview of Collections

Collections are fundamental data structures used to store, retrieve, and manipulate groups of objects. The .NET Framework provides a rich set of collection classes in the System.Collections and System.Collections.Generic namespaces. Using generic collections (those in System.Collections.Generic) is generally preferred due to type safety and improved performance.

Key Collection Interfaces

Common Generic Collection Types

Lists (List<T>)

A List<T> is a resizable array that allows duplicate elements and maintains the order of elements. It's one of the most commonly used collection types.

Example: Using List<T>

using System;
using System.Collections.Generic;

public class ListExample
{
    public static void Main(string[] args)
    {
        List<string> fruits = new List<string>();
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Orange");

        Console.WriteLine("First fruit: " + fruits[0]); // Output: Apple

        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }

        fruits.Remove("Banana");
        Console.WriteLine("Count after removal: " + fruits.Count); // Output: 2
    }
}

Dictionaries (Dictionary<TKey, TValue>)

A Dictionary<TKey, TValue> stores key-value pairs, where each key must be unique. It provides fast lookups based on the key.

Example: Using Dictionary<TKey, TValue>

using System;
using System.Collections.Generic;

public class DictionaryExample
{
    public static void Main(string[] args)
    {
        Dictionary<int, string> studentGrades = new Dictionary<int, string>();
        studentGrades.Add(101, "Alice");
        studentGrades.Add(102, "Bob");
        studentGrades.Add(103, "Charlie");

        Console.WriteLine("Student with ID 102: " + studentGrades[102]); // Output: Bob

        if (studentGrades.ContainsKey(104))
        {
            Console.WriteLine("Student 104 found.");
        }
        else
        {
            Console.WriteLine("Student 104 not found."); // Output: Student 104 not found.
        }
    }
}

Sets (HashSet<T>)

A HashSet<T> stores a collection of unique elements, meaning duplicate elements are not allowed. It offers fast add, remove, and contains operations.

Note:

Unlike List<T>, HashSet<T> does not maintain the order of insertion and does not allow access by index.

Queues (Queue<T>)

A Queue<T> implements a First-In, First-Out (FIFO) collection. Elements are added to the end of the queue and removed from the beginning.

Stacks (Stack<T>)

A Stack<T> implements a Last-In, First-Out (LIFO) collection. Elements are added to the top of the stack and removed from the top.

Non-Generic Collections

The System.Collections namespace contains non-generic collection types, such as ArrayList, Hashtable, Queue, and Stack. While they can still be used, they are generally discouraged in modern C# development in favor of their generic counterparts due to the lack of type safety and potential for runtime boxing/unboxing overhead.

Collection Type Namespace Description Key Features
List<T> System.Collections.Generic Resizable array Ordered, allows duplicates, indexed access
Dictionary<TKey, TValue> System.Collections.Generic Key-value pairs Unique keys, fast lookups
HashSet<T> System.Collections.Generic Unique elements No duplicates, fast add/remove/contains
Queue<T> System.Collections.Generic FIFO (First-In, First-Out) Enqueue/Dequeue operations
Stack<T> System.Collections.Generic LIFO (Last-In, First-Out) Push/Pop operations
ArrayList System.Collections Resizable array (non-generic) Less type-safe, potential boxing/unboxing
Hashtable System.Collections Key-value pairs (non-generic) Less type-safe, potential boxing/unboxing

Important:

Always prefer using generic collections (from System.Collections.Generic) over non-generic ones whenever possible to leverage type safety and improve performance.