Dictionary in C#

A dictionary is a data structure in C# that is similar to the hash-table (a collection used to store key-value pairs). In a dictionary, we cannot have duplicate or null keys, but we can have duplicate or null values.

svg viewer

Syntax

The first argument specifies the key type and the second is for the value type.

Dictionary <dataType, dataType> dictionary = new Dictionary<dataType, dataType>();

Remember: Dictionary collection is implemented in the class System.Collection.Generics.

Basic methods

Method Description
1.Add(key, value) Used to insert a key-value pair in a dictionary.
2.Remove(key) Used to remove a pair with a specified key.
3.ConatinsKey(key) Used to check whether or not a specified key exists in the dictionary.
4.ConatinsValue(value) Used to check whether or not a specified value exists in the dictionary.
5.Clear() Used to remove all the pairs from the dictionary.

Code

using System;
using System.Collections.Generic;
class DictionaryTesting
{
static void Main()
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
// Add(key, value) Method
dictionary.Add(1,"John");
dictionary.Add(2,"Cassy");
dictionary.Add(3,"Peter");
dictionary.Add(4,"Luis");
dictionary.Add(5,"Flash");
// Printing dictionary
System.Console.WriteLine("Dictionary after adding pair:");
foreach(KeyValuePair<int, string> temp in dictionary)
{
Console.WriteLine("Key {0} and Value {1}", temp.Key, temp.Value);
}
// Remove(key) Method
dictionary.Remove(4);
// Printing dictionary
System.Console.WriteLine("Dictionary after removing pair with key 4:");
foreach(KeyValuePair<int, string> temp in dictionary)
{
Console.WriteLine("Key {0} and Value {1}", temp.Key, temp.Value);
}
// ConatinsKey(key) Method
System.Console.WriteLine("Dictionary has any pair with the key = 5?");
System.Console.WriteLine(dictionary.ContainsKey(5));
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved