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.


c# dictionary sample

Parameters :

  • TKey - The type of the keys in the dictionary.
  • TValue - The type of the values in the dictionary


Dictionary<string, string>
	Dictionary<string, int>

Adding Values to Dictionary:

  • Add method in Dictionary takes two parameters, one for the key and one for the value.


public void Add(TKey key,TValue value)


  • Key in a Dictionary should not be null, but a value can be, if TValue is a reference type.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);
dict.Add("three", 3);
dict.Add("four", 4);

Retrieve Key-Value pair from Dictionary:

learn c# tutorials - dictionary in csharp - c# programs

dictionary in csharp

  • We can retrieve values from Dictionary using foreach loop
foreach (KeyValuePair<string, int> pair in dict)
    MessageBox.Show(pair.Key.ToString ()+ "  -  "  + pair.Value.ToString () );

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
using System;  
using System.Collections.Generic;  
public class DictionaryExample  
    public static void Main(string[] args)  
        Dictionary<string, string> names = new Dictionary<string, string>();  
        foreach (KeyValuePair<string, string> kv in names)  
            Console.WriteLine(kv.Key+" "+kv.Value);  

C# examples - Output :

1 Sonoo
2 Peter
3 James
4 Ratan
5 Irfan

Related Searches to C# Dictionary