typestar

Dictionaries in C#

Key to value in constant time, with a safe way to ask for what might be missing.

var ages = new Dictionary<string, int>
{
    ["Ada"] = 36, ["Grace"] = 45, ["Alan"] = 41,
};
ages["Edsger"] = 72;

// TryGetValue avoids the exception a missing key would throw
if (ages.TryGetValue("Grace", out var age))
{
    Console.WriteLine($"Grace is {age}");
}
foreach (var (name, years) in ages)
{
    Console.WriteLine($"{name}: {years}");
}

How it works

  1. The index initializer reads like the lookups it will serve.
  2. TryGetValue avoids the exception a missing key would throw.
  3. foreach over a dictionary deconstructs each pair into name and value.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
337
Tokens
79
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 3 of 4 in Collections, step 13 of 29 in Language basics.

← Previous Next →

Dictionaries in other languages