System.Collections.Generic Namespace

Namespace: System.Collections.Generic

Provides interfaces and classes that define generic collections, which allow developers to create strongly typed collections that improve type safety and performance by enabling the collection to be constrained to specific types.

Summary

The System.Collections.Generic namespace contains fundamental interfaces and classes for generic collections. These collections are designed to be type-safe, meaning they can only store objects of a specified type, preventing runtime type errors. This leads to more robust and performant code compared to non-generic collections.

Core Interfaces

Interfaces

Core Classes

Common Usage Patterns

Generic collections are widely used in .NET development for managing groups of objects efficiently and safely. Some common scenarios include:

  • Storing a list of user objects: List<User>
  • Mapping configuration keys to values: Dictionary<string, string>
  • Implementing a FIFO (First-In, First-Out) queue for processing items: Queue<Order>
  • Managing a LIFO (Last-In, First-Out) stack for undo/redo operations: Stack<Command>

Example


using System;
using System.Collections.Generic;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a strongly-typed list of strings
        List names = new List();
        names.Add("Alice");
        names.Add("Bob");
        names.Add("Charlie");

        Console.WriteLine("Names:");
        foreach (string name in names)
        {
            Console.WriteLine($"- {name}");
        }

        // Create a dictionary mapping product IDs to prices
        Dictionary prices = new Dictionary();
        prices.Add(101, 19.99m);
        prices.Add(205, 5.50m);

        Console.WriteLine("\nProduct Prices:");
        foreach (var pair in prices)
        {
            Console.WriteLine($"Product ID: {pair.Key}, Price: {pair.Value:C}");
        }
    }
}