Roadmap › C# Language — Basics to Advanced › Module: Arrays and Collections
Lessons in this course (38)
13. ArrayList and Hashtable (legacy non-generic collections)
BasicMediumLesson 13 of 38
You will meet these in old .NET Framework code and in interviews.
csharp
using System.Collections;
var list = new ArrayList();
list.Add(1); // boxed to object
list.Add("two"); // anything goes — no type safety
list.Add(3.5);
foreach (object o in list) Console.WriteLine(o);
int first = (int)list[0]!; // cast needed; wrong cast → InvalidCastException at runtime
var table = new Hashtable();
table["IN"] = "India";
table["TW"] = "Taiwan";
table["IN"] = "Bharat"; // overwrite
Console.WriteLine(table["XX"] == null); // True — missing key returns null (Dictionary throws)
foreach (DictionaryEntry e in table) Console.WriteLine($"{e.Key} = {e.Value}");ArrayList | List<T> | Hashtable | Dictionary<K,V> | |
|---|---|---|---|---|
| Type safety | ❌ object | ✅ | ❌ object | ✅ |
| Boxing of value types | Yes | No | Yes | No |
| Missing key | — | — | Returns null | Throws (use TryGetValue) |
| Thread safety | ArrayList.Synchronized wrapper | No (use concurrent collections) | Safe for many readers + one writer | No |
Interview tip: "Hashtable vs Dictionary" — Dictionary is generic (type-safe, no boxing, faster); a missing key throws in Dictionary but returns null in Hashtable; both are hash-based with O(1) average lookup. Use
ConcurrentDictionaryfor multi-threaded writes.