C# Interview Question #36

What is Dictionary<TKey, TValue> in C#?

Generics & Collections Mid-Level Intermediate

Quick Interview Answer

Dictionary<TKey,TValue> stores data as key-value pairs. Each key must be unique, and values are retrieved using their associated keys.

Detailed Explanation

Dictionary<TKey,TValue> stores data as key-value pairs. Each key must be unique, and values are retrieved using their associated keys.

Dictionary lookup is generally very efficient and is useful when data must be accessed by an identifier rather than by numeric position.

TryGetValue is commonly preferred when a key may not exist because it avoids performing a separate existence check followed by another lookup.

Code Example

Dictionary<int, string> users = new()
{
    [1] = "Ali",
    [2] = "Ahmed"
};

if (users.TryGetValue(2, out string? name))
{
    Console.WriteLine(name);
}