System.Collections Namespace
The
System.Collections namespace contains interfaces and classes that define nongeneric collections of objects, such as lists, dictionaries, and hash sets. This namespace is part of the core .NET Framework and is fundamental for data manipulation in C#.
Interfaces
Classes
- ArrayList - Represents a strongly typed list of objects that can be accessed by index. Provides methods for searching, sorting, and manipulating lists.
- BitArray - Represents a compacted array of bits that are represented as Boolean values.
- CaseInsensitiveComparer - Compares two objects for equality, ignoring the case of strings.
- DictionaryBase - Provides a basic implementation of the IDictionary interface.
- Hashtable - Represents a collection of key/value pairs that are organized by hash code. This collection is not strongly typed.
- ListBase - Provides a base class for custom list collections.
- Queue - Represents a first-in, first-out (FIFO) collection of objects.
- SortedList - Represents a collection of key/value pairs that are sorted by key and are accessible by index.
- Stack - Represents a variable-size run-time stack of objects.
Other Types
- CollectionBase - Provides a base class for custom list collections that can be strongly typed.
- DictionaryEntry - Represents a key/value pair that can be edited.
- ReadOnlyCollectionBase - Provides a base class for custom read-only collections that can be strongly typed.
Common Use Cases
The System.Collections namespace is essential for:
- Storing and retrieving groups of objects.
- Implementing data structures like stacks, queues, and hash tables.
- Working with nongeneric collections, especially in older codebases or when interoperating with COM.
Note on Generics
For new development in C#, it is highly recommended to use the generic collections found in the System.Collections.Generic namespace (e.g., List<T>, Dictionary<TKey, TValue>). Generic collections provide better type safety and performance.
Example of using ArrayList (nongeneric):
using System.Collections;
public class NongenericExample
{
public static void Main(string[] args)
{
ArrayList myList = new ArrayList();
myList.Add("Hello");
myList.Add(123);
myList.Add(true);
foreach (object item in myList)
{
Console.WriteLine(item);
}
}
}