System.Collections Namespace

The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables, and dictionaries.

Overview

Collections are fundamental to .NET programming. They provide a way to store groups of related objects and enable you to iterate over them efficiently.

  • ArrayList – dynamically sized array of objects.
  • Hashtable – collection of key/value pairs that are organized based on the hash code of the key.
  • Queue – first‑in, first‑out collection.
  • Stack – last‑in, first‑out collection.
  • SortedList – key/value pairs sorted by key.
  • BitArray – compact array of Boolean values.

Key Classes

ArrayList

A dynamically resizable array of object references.

// Example: Using ArrayList
using System.Collections;

ArrayList list = new ArrayList();
list.Add(1);
list.Add("two");
list.Add(3.0);

foreach (var item in list)
{
    Console.WriteLine(item);
}

Hashtable

Stores key/value pairs for fast lookup by key.

// Example: Using Hashtable
using System.Collections;

Hashtable table = new Hashtable();
table["one"] = 1;
table["two"] = 2;

Console.WriteLine(table["one"]); // 1

Queue

Provides FIFO (first‑in, first‑out) collection semantics.

// Example: Using Queue
using System.Collections;

Queue q = new Queue();
q.Enqueue("first");
q.Enqueue("second");
Console.WriteLine(q.Dequeue()); // first

Stack

Provides LIFO (last‑in, first‑out) collection semantics.

// Example: Using Stack
using System.Collections;

Stack s = new Stack();
s.Push(10);
s.Push(20);
Console.WriteLine(s.Pop()); // 20

SortedList

Key/value pairs sorted by key based on the key's IComparable implementation.

// Example: Using SortedList
using System.Collections;

SortedList list = new SortedList();
list.Add("b", 2);
list.Add("a", 1);
foreach (DictionaryEntry entry in list)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

BitArray

Efficient storage of Boolean values as bits.

// Example: Using BitArray
using System.Collections;

BitArray bits = new BitArray(8);
bits[0] = true;
bits[1] = false;
bits[2] = true;

foreach (bool b in bits)
{
    Console.WriteLine(b);
}

Important Interfaces

  • ICollection – base interface for non‑generic collections.
  • IEnumerable – provides iteration over a collection.
  • IList – ordered collection that can be accessed by index.
  • IDictionary – collection of key/value pairs.
  • IComparer – defines a method that compares two objects.
  • IEqualityComparer – defines methods to compare objects for equality.