All lessons

Dictionaries

8 min · C#

Look up values by key with Dictionary, C#'s map.

C# · Dictionaries0/5 cleared

Enemy 1 of 5

Looking things up by key

This code makes a Dictionary that stores a score under the key "Ada", then reads it back by that key instead of a number position. Press Run to see 10.

Why this works

A List gives you lookups by position (index 0, 1, 2...). A Dictionary<TKey, TValue> instead lets you look values up by a meaningful key (a player's name, an item id) rather than a numeric position. Like List<T>, the type parameters lock down exactly what types of keys and values are allowed, so the compiler can catch mismatches for you.

new Dictionary<string, int>() creates an empty dictionary; .Add(key, value) inserts a new entry, and [key] reads a value back by its key. If you try to read a key that was never added, .Add or [] will throw an exception rather than silently returning a default, worth remembering, since it's different behavior from some other languages' dictionaries.

This exact key-value idea appears in nearly every language under a different name: a dict in Python, an object or Map in JavaScript, a map in Go. Dictionary is C#'s version of the same universally useful structure.

You
Goblin Glitch
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.