Easy Start to Dictionary in C#

Haydar Ali Ismail
2 min readFeb 11, 2017

Most of the time when we develop applications we will need to store information to array or list. However, sometimes storing the whole thing into an array is not the best method. When we need to get or add a specific value we need to specify an index, which might change over time. Thus, for some cases, there is a better way to store those data so that we do not have to iterate through the array or list.

Introducing Dictionary

One of the solutions is using a dictionary. A dictionary consists of two pairs of values: key and value. The flexibility of using a dictionary is that we can define the file type for the key and value. So, we are not restricted to a specific file type of key such as an integer. Without further ado, let’s try it.Creating Dictionary

Initializing a dictionary is pretty easy, we can use the syntax of Dictionary<key-file-type, value-file-type>. Let’s say we want to create a dictionary of fruits with string as the key and integer as the value for the available quantity in a store.

Pretty easy right?

Check and Get Value from Dictionary

Now, we already know how to store those values. But, how to get those values back? To check if a particular key exists, we can use a method called ContainsKey(key). Then after that, when we are sure that the key and value pair is in the dictionary, we can get it using index-like just what we used to do when accessing from an array. We will use something like dictionary[“key”]. An example of that is available below.

Wrap Up

So, today we have talked about an alternative to storing list of information to a variable. The alternative is called dictionary where we can store a key-value pair to it. To search and fetch for the specific value, we can just use the key and the dictionary will handle it.

--

--