Member-only story
Hi everyone, welcome back. In these examples, we will be going over Dictionaries in C#. Dictionaries can be used to store a collection of data, similar to that of a normal list. The main difference is that a Dictionary can store elements as key/value pairs as an alternative to using index numbers. The keys must be unique and cannot be null where the values can be duplicates or be null. With this introduction out of the way, let’s get into it.
Creating Dictionary
Let’s start by creating a Dictionary. Before we can create a Dictionary, we need to make sure that we have our Dictionary import, which is included within the System.Collections.Generic package:
using System.Collections.Generic;
Now, we can successfully create our Dictionary:
Dictionary<int, string> myDict = new Dictionary<int, string>();
So now, we have created our Dictionary variable. Our keys are of the ‘int’ data type and our values are of the ‘string’ data type. When we create our Dictionary, we will need to specify that data types for our keys and values. We can use other data types as well for both.