Dictionary<TKey, TValue> is a collection of keys and values, where key value must be unique to Dictionary and value must not be null. Dictionary<TKey, TValue> is an reference type. System.Collections.Generic class methods that we can use with Dictionary<TKey, TValue>.

Declaration

Dictionary<TKey, TValue> can can contain reference or value types. We declare a Dictionary<TKey, TValue>  by typing Dictionary followed by<> (angle brackets) and inside <> first type should be our key type and second should be type of our value desired type of our Dictionary and after that should be variable name:

Initialization

As Dictionary< TKey, TValue > is an reference type so we initialize it by assigning Dictionary variable to Dictionary instance. Types of key and value should be specified while instantiating Dictionary.

Populating a Dictionary<TKey,TValue>

with values

Add element to end of a Dictionary

Using collection initializer

Remove an element from the Dictionary<TKey,TValue> by key value

How to use generic Dictionary<TKey,TValue>

Retrieve value by index

We retrieve an element from Dictionary<TKey,TValue> by specifying value of that key. If for example we wanted to retrieve element with key value 1 from our previous Dictionary we can access that value like this:

Of course if we have Dictionary of objects we can specify value of an element and select property to display.

We can check if value exist with ContainsKey method.

We can check if key exist with ContainsValue method.

We can also check if key exists and if the key exists retrieve it’s value in one run using TryGetValue method. Note that if key does not exist exception will not be thrown.

Iterate through Dictionary<TKey,TValue>

We can iterate an Dictionary using for and foraech statements

Number of elements inside of a Dictionary<TKey,TValue>