Search⌘ K
AI Features

Dictionary

Explore how to work with the C# Dictionary collection to store and retrieve key-value pairs efficiently. Learn the syntax for creating dictionaries, adding and accessing elements, and handling keys with methods such as Add, TryAdd, and TryGet. Understand the importance of unique keys and the flexibility of values through practical examples.

We'll cover the following...

Overview

Dictionaries are key-value stores. These are mappings between keys and associated values. We can imagine a dictionary as a book where we have words and associated translations. Words are keys and translations are values:

%0 node_2 White node_1639590737864 Blanco node_2->node_1639590737864 node_1 House node_1_1 La Casa node_1->node_1_1 node_0 Hello node_0_1 Hola node_0->node_0_1
An example of a dictionary

Keys in .NET dictionaries must be unique. It’s impossible to have two identical keys. Values aren’t unique, though.

Syntax

Dictionaries in .NET are created by instantiating the Dictionary<K, V> class. We can use any type as a key and any type as a value:

 ...