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.
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:
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: