Introduction and Background
In this article, we are going to dive into the world of dictionaries using C#. Dictionaries are exciting to learn, especially if you are already familiar with arrays and lists. However; before proceeding I highly recommend knowing and understanding the basics of arrays and/or lists, but it doesn’t hurt if you decided to continue.
In years of my experience creating software, I’ve seen developers who really love arrays and lists. However; many of them aren’t comfortable using dictionaries. That’s why I decided to write one about dictionaries using C# and, in this post, will try to tackle most of the basics so it can help you get started.
What is a Dictionary?
In the context of programming, a dictionary is basically a collection of keys and values. So key-value pair collection has a set of keys and each key has an associated value to it. Within the .NET framework/.NET Core, a dictionary class provides an indexed way of looking up values by key e.g. fruits["mango"]. Unlike list and arrays are accessed using a positional index number e.g. fruits[0].
Things to remember about Dictionary,
- Dictionaries can’t have same keys
- Dictionaries can’t have null keys
Dictionary using C# 101
Ways to instantiate a Dictionary
- IDictionary<string, string> countries = new Dictionary<string, string>();
- Dictionary<string, string> asianCountries = new Dictionary<string, string>();
As you can see the above statements are valid to create a new instance of a Dictionary.
You could either choose any of the two, just choose one for your personal preference or your team's preference.
Now to test if the two statements are valid, see a unit test code below.
- [Fact]
- public void Test_Dictionary_Different_Ways_To_Create_A_New_Instance()
- {
- IDictionary<string, string> countries = new Dictionary<string, string>();
- Assert.NotNull(countries);
- Dictionary<string, string> asianCountries = new Dictionary<string, string>();
- Assert.NotNull(asianCountries);
- }
I know you're excited to see how to create a dictionary and see different ways to initialize it.
Let us see some code samples below.
- Dictionary<string, string> asianCountries = new Dictionary<string, string>();
- asianCountries.Add("PH", "Philippines");
- Dictionary<string, string> asianCountries2 = new Dictionary<string, string>
- {
- { "PH", "Philippines" }
- };
- Dictionary<string, string> asianCountries3 = new Dictionary<string, string>
- {
- ["PH"] = "Philippines"
- };
- [Fact]
- public void Test_Dictionary_Different_Ways_To_Create_A_New_Instance_And_Initialize()
- {
- Dictionary<string, string> asianCountries = new Dictionary<string, string>();
- asianCountries.Add("PH", "Philippines");
- Dictionary<string, string> asianCountries2 = new Dictionary<string, string>
- {
- { "PH", "Philippines" }
- };
- Dictionary<string, string> asianCountries3 = new Dictionary<string, string>
- {
- ["PH"] = "Philippines"
- };
- Assert.NotNull(asianCountries);
- Assert.NotNull(asianCountries2);
- Assert.NotNull(asianCountries3);
- }
In this section, will try to see how to add items within a dictionary collection.
Let us discuss the usage of the Add() and TryAdd() method. These two behave differently, just remember that when you try to use the Add() method it will definitely throw an exception when a key already exists. However; the TryAdd() method will try its best to add the new item and returns if it was successfully added or not. Lastly, both methods will throw an exception when the passed key is null.
Let us see the behaviors of these two methods via adding an existing key and passing a null key value by looking at the sample codes below.
- [Fact]
- public void Test_Dictionary_Cant_Have_A_Null_Key()
- {
- Dictionary<string, string> nullDictionary = new Dictionary<string, string> { };
- nullDictionary.Add("USA", null); //passed when adding a null value
- //throws an exception when adding a null as key
- Assert.Throws<ArgumentNullException>(() => nullDictionary.Add(null, null));
- Assert.Throws<ArgumentNullException>(() => nullDictionary.TryAdd(null, null));
- }
- [Fact]
- public void Test_Dictionary_Cant_Have_Same_Key()
- {
- Dictionary<string, string> sampleDictionary = new Dictionary<string, string>();
- sampleDictionary.Add("MJ", "Michael Jordan");
- //throws an exception when adding an existing key
- Assert.Throws<ArgumentException>(() => sampleDictionary.Add("MJ", "Magic Johnson"));
- //TryMethod tries to add a new key but fails because MJ already exists
- Assert.False(sampleDictionary.TryAdd("MJ", "Magic Johnson"));
- }


Sourav Kumar DasPosted Jan 2, 2020, 6:29 AM
Nice and useful article.