Dictionary<TKey, TValue> (C#)

A Dictionary<TKey, TValue> stores data as key–value pairs, letting you look up a value by its unique key instead of by position. It is C#'s version of a hash map.

C#

Each key must be unique. You read and write values with square-bracket indexing using the key, and check for a key with .ContainsKey() or .TryGetValue().

Dictionaries are extremely fast for lookups and live in the System.Collections.Generic namespace alongside List<T>.

Syntax

Dictionary<TKey, TValue> name = new Dictionary<TKey, TValue>();

Examples

C#

var user = new Dictionary<string, int>();
user["Ana"] = 30;
user["Ben"] = 25;
Console.WriteLine(user["Ana"]);

Output:

30

Learn it in a lesson

See also

Back to the Dictionary