C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Dictionary

C# Dictionary

Dictionary<TKey, TValue> stores key-value pairs with O(1) average lookup time.

1 - Creating and Adding

var scores = new Dictionary<string, int>
{
    ["Alice"] = 95,
    ["Bob"]   = 87,
};
scores["Carol"] = 92;
scores.Add("Dave", 78);

Console.WriteLine(scores["Alice"]); // 95
Console.WriteLine(scores.Count);    // 4

2 - Safe Access

// TryGetValue — avoids KeyNotFoundException
if (scores.TryGetValue("Eve", out int eveScore))
    Console.WriteLine($"Eve: {eveScore}");
else
    Console.WriteLine("Eve not found");

// GetValueOrDefault (C# 8+)
int carolScore = scores.GetValueOrDefault("Carol", 0); // 92

3 - Iterating

foreach (var (name, score) in scores)
    Console.WriteLine($"{name}: {score}");

// Keys and Values
foreach (string key   in scores.Keys)   Console.WriteLine(key);
foreach (int    value in scores.Values) Console.WriteLine(value);

4 - Removing and Checking

scores.ContainsKey("Alice");  // true
scores.ContainsValue(95);     // true
scores.Remove("Dave");
scores.Clear();

Note: Always use TryGetValue instead of indexer access when you are not sure whether a key exists. Accessing a missing key with the indexer throws a KeyNotFoundException.

-Tip-