System.Collections Namespace

Provides interfaces and classes that define loosely typed collections of objects.
The classes in the System.Collections namespace represent collections of objects, such as lists, queues, dictionaries, and sets. These classes are fundamental for many programming tasks, enabling efficient storage, retrieval, and manipulation of groups of related data. The interfaces in this namespace are the foundation upon which generic collections (in System.Collections.Generic) are built.

Key Concepts and Interfaces

The System.Collections namespace defines several core interfaces that describe the behavior of collections:

Important Classes

This namespace includes several non-generic collection classes:

ArrayList

Represents a dynamically-sized array of objects. It is similar to an array but can grow or shrink as needed. Items are stored as object, requiring casting.

Queue

Represents a first-in, first-out (FIFO) collection of objects. Items are added to the end and removed from the beginning.

Stack

Represents a last-in, first-out (LIFO) collection of objects. Items are added to the top and removed from the top.

Hashtable

Represents a collection of key/value pairs that are organized by hash codes. This is a non-generic dictionary implementation.

SortedList

Represents a collection of key/value pairs that are sorted by key. It offers both indexed and key-based access.

DictionaryBase

An abstract base class for implementing custom dictionary collections.

Usage and Best Practices

Note: For new development in .NET, it is strongly recommended to use the generic collections found in the System.Collections.Generic namespace (e.g., List<T>, Dictionary<TKey, TValue>). Generic collections provide type safety, improved performance by eliminating boxing/unboxing operations, and a more robust development experience. The non-generic collections in System.Collections are primarily for backward compatibility or specific scenarios where type flexibility is paramount and performance impact is understood.

Example: Using ArrayList

Here's a simple example demonstrating how to use ArrayList:

// C# example using System.Collections; using System; 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} (Type: {item.GetType().Name})"); } // Accessing an item (requires casting) string firstItem = (string)myList[0]; Console.WriteLine($"First item as string: {firstItem}"); } }

Related Topics