Collections & Generics
Unlike raw fixed arrays, C# generic collections dynamically resize automatically and provide type safety, avoiding expensive boxing/unboxing overhead.
1 Collection Architecture: List, Dictionary, and HashSet
Common generic containers in the `System.Collections.Generic` namespace include:
- List<T>: A dynamic, ordered list of items.
- Dictionary<TKey, TValue>: Stores unique key-value pairs for quick lookups.
- HashSet<T>: An unordered collection containing only unique elements.
2 Collections Code
Let's run a program performing list inserts, unique set operations, and key-value lookups:
C# — Generic Collections
▶ Run Code
using System;
using System.Collections.Generic;
class Program {
static void Main() {
// 1. List
List<string> list = new List<string>() { "Apple", "Banana" };
list.Add("Apple"); // Duplicates allowed
Console.WriteLine("List count: " + list.Count);
// 2. HashSet
HashSet<string> set = new HashSet<string>() { "Apple", "Banana" };
set.Add("Apple"); // Duplicate ignored
Console.WriteLine("HashSet count: " + set.Count);
// 3. Dictionary (Key-Value)
Dictionary<string, int> map = new Dictionary<string, int>();
map["Alice"] = 95;
map["Bob"] = 88;
Console.WriteLine("Bob's score: " + map["Bob"]);
}
}
3 Code Challenge
Challenge: Write a program that instantiates a `List`, adds 5 values, removes the value at index 2, and prints the remaining items. Create a `Dictionary` mapping products to prices and print the price values.