C# Dictionary - c# - c# tutorial - c# net
What is dictionary in C# ?
- C# Dictionary<TKey, TValue> class uses the concept of hashtable.
- It stores values on the basis of key.
- It contains unique keys only.
- By the help of key, we can easily search or remove elements.
- It is found in System.Collections.Generic namespace.
Syntax:
Parameters :
- TKey - The type of the keys in the dictionary.
- TValue - The type of the values in the dictionary
Example
Adding Values to Dictionary:
- Add method in Dictionary takes two parameters, one for the key and one for the value.
Syntax:
Example
- Key in a Dictionary should not be null, but a value can be, if TValue is a reference type.
Retrieve Key-Value pair from Dictionary:
dictionary in csharp
- We can retrieve values from Dictionary using foreach loop
C# Dictionary<TKey, TValue> example:
- Let's see an example of generic Dictionary<TKey, TValue> class that stores elements using Add() method and iterates elements using for-each loop.
- Here, we are using KeyValuePair class to get key and value