System.Collections Namespace
Namespace
Provides fundamental interfaces and classes for collections, such as lists, dictionaries, and sets.
Namespace: System.Collections
Assembly: System.Private.CoreLib
Members
- IList Interface Represents a strongly typed list of objects that can be accessed by index.
- ICollection Interface Represents a collection of objects.
- IEnumerable Interface Exposes the enumerator, which supports a simple iteration over a non-generic collection.
- IDictionary Interface Represents a collection of key/value pairs.
- IEnumerator Interface Supports a simple iteration over a non-generic collection.
- ArrayList Class Represents a resizable array of objects.
- Hashtable Class Represents a collection of key and value pairs that are organized by the hash code of the key.
- Queue Class Represents a first-in, first-out (FIFO) collection of objects.
- Stack Class Represents a variable-size stack of objects.
Introduction
The System.Collections
namespace contains interfaces and classes that define how to work with collections of objects. These include fundamental types like lists, dictionaries, queues, and stacks. This namespace was part of the original .NET Framework and provides non-generic collection types. While newer, generic versions exist in System.Collections.Generic
, these classes are still widely used and understood in older codebases.
Key Interfaces
Several key interfaces define the contracts for collection behavior:
IEnumerable
: Allows objects to be iterated over, typically using aforeach
loop.ICollection
: ExtendsIEnumerable
by providing properties for size and synchronization, and methods for adding, removing, and copying elements.IList
: ExtendsICollection
by providing indexed access to elements, similar to an array.IDictionary
: Represents a collection where elements are stored as key-value pairs, accessed by their unique keys.IEnumerator
: Provides a mechanism to step through a collection, retrieving elements one by one.
Common Classes
The namespace also includes concrete implementations of these interfaces:
ArrayList
: A dynamic array that can grow or shrink as needed. It can store elements of any type.Hashtable
: Implements a dictionary using hashing for efficient key-based lookups.Queue
: Implements a First-In, First-Out (FIFO) data structure.Stack
: Implements a Last-In, First-Out (LIFO) data structure.
Usage Example (ArrayList)
using System;
using System.Collections;
public class Example
{
public static void Main(string[] args)
{
ArrayList myList = new ArrayList();
myList.Add("Hello");
myList.Add(123);
myList.Add(true);
Console.WriteLine($"Number of items: {myList.Count}");
foreach (object item in myList)
{
Console.WriteLine($"Item: {item}");
}
// Access by index
Console.WriteLine($"First item: {myList[0]}");
}
}