System.Collections Namespace
The System.Collections namespace provides the base classes and interfaces for nonāgeneric collections in .NET. These collections store objects of type object and are primarily maintained for backward compatibility. For new development, the generic equivalents in System.Collections.Generic are recommended.
Key Types
- ArrayList ā Dynamically sized array of objects.
- Hashtable ā Key/value map using hashing.
- Stack ā LIFO collection.
- Queue ā FIFO collection.
- SortedList ā Sorted key/value pairs.
Example: Using ArrayList
Program.cs
using System;
using System.Collections;
class Program
{
static void Main()
{
// Create an ArrayList and add heterogeneous items
ArrayList items = new ArrayList();
items.Add(10);
items.Add("hello");
items.Add(DateTime.Now);
foreach (object o in items)
{
Console.WriteLine($"{o} ({o.GetType()})");
}
// Insert at a specific index
items.Insert(1, 3.14);
Console.WriteLine("\nAfter Insert:");
foreach (var o in items) Console.WriteLine(o);
}
}
When to Use NonāGeneric Collections
Nonāgeneric collections are useful when you need to store heterogeneous types or when working with legacy code that predates .NET 2.0. However, they incur boxing/unboxing overhead for value types and lack compileātime type safety.