C# Dictionary With Examples

Shahzad Aslam
2 min readFeb 11, 2024
C# Dictionary With Examples

The Dictionary is related to System.Collections.Generic namespace. Dictionary contains on key-value pairs. Where each key is associated with a unique value. Dictionary can store specific type value for example if you are making a dictionary of int type then it can only store integer type values. On other hand hashtable can store any data type value.

Features with dictionary in C#:

Creating a Dictionary:

You need to import the System.Collections.Generic namespace to work with a Dictionary. To create a Dictionary, you can use the following code.

using System;
using System.Collections.Generic;
Dictionary<string,int> dictfruitprices = new Dictionary<string,int>();
Dictionary<string,string> dictfruitnames = new Dictionary<string,string>();

Adding Key-Value Pairs:

You can add key-value pairs to a Dictionary using the Add method or by using the indexer.

dictfruitprices.Add("Apple",16);
dictfruitprices.Add("Orange",12);
dictfruitprices.Add("Cherry",18);
dictfruitprices["Papaya"] = 20;
dictfruitprices["Grape"] = 6;
dictfruitnames.Add("Apple","Red");
dictfruitnames.Add("Mango","Yellow");
dictfruitnames.Add("Cherry","Red");
dictfruitnames.Add("Orange","Dark Orange");
dictfruitnames["Grape"] = "Violet"…

--

--

Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.