Home » C# Tutorial » All You Need to Know About C# Dictionary

All You Need to Know About C# Dictionary

Like most of us, you too may be on your way to improve your knowledge of one particular programming language or to start your journey with a completely different coding script. Regardless of which one, what you want and what you most definitely need is a helpful, trustworthy, and reliable guide. With the right guide, learning absolutely anything seems fun and exciting and makes you want to know more with every passing minute. Let us assume that you wished to learn a new spoken language. What would be your most valuable asset in this case? Your trusty friend, a dictionary. In exactly the same way, if you were to attempt to learn a programming language, in this case, C#, your most precious asset would be a C# dictionary (pronounced as Csharp dictionary)

In essence, that is all there is to it, but we may still need to understand how to go about reading this dictionary. So, without further ado, let us begin!

What is a C# Dictionary? 

Like a textbook dictionary, the C# dictionary is a collection of keys and values, in which a key is like a word and a value is akin to a definition. A dictionary class is mainly present in System.Collections.Generic namespace. This will be further in this article. When creating a dictionary, we need to specify the type of key and value.

A dictionary provides fast lookups for values using keys. Another factor to remember is that every key in the dictionary must be unique. In this article, we will teach you how to create a generic dictionary that can store any type of data. Simply put, a key is a ‘string’ data type, however, the values within that string can be an integer, float, double, or another string. 

using System.Collections.Generic;
namespace Demo
{
class Program
{
private static Dictionary<string, object> dict;
// ‘dict’ is the name we have associated with our C# dictionary example
static void Main(string[] args) 
{
// To substantiate the creation of the dictionary, we need to declare it as follows:
dict = new Dictionary<string, object>();

}
}
}

The next step here is to add a function that allows us to add the key and object to our newly created dictionary. To do so, you need to make the following changes in your code:

class Program
{
private static Dictionary<string, object> dict;
private static void Add(string strKey, object dataType)
// When we add data to our dictionary, we often need to check if that key already exists with our C# dictionary or not. The following method shows you how to do exactly that with the use of a condition.
{ 
if (!dict.ContainsKey(strKey))
{
Dict.Add(strKey, dataType);
}
Else
{
dict[strKey] = dataType;
}
}
}

This is the method to add the key, in this case, the strKey to this C# dictionary example and associate it with its value, that is, ‘dataType’ Now that you have successfully stored the value ‘dataType’ into the key ‘strKey,’ it is time to learn how to retrieve that value from the key that it has been assigned to. With the following method, you can retrieve the value that you may be looking for from a specific key from the dictionary that you have established.

// add this after the if/else condition
private static T GetAnyValue<T>(string strKey)
{
object abc;
T retype;
dict.TryGetValue(strKey, out abc);
//now that you have defined an object ‘abc’ around which you can base your function, your next step will be to cast the return type ‘retType’ The ‘catch’ keyword is used to offset any exception that may be thrown due to any reason.
try
{
retype = (T)abc;
}
catch
{
retype = default(T);
}
return retType;
}

Now you have completed all the steps to create a function that will recall the value that you have assigned to any key within your C# dictionary. Since we have the fundamentals down pat, let us move on to practicing with a few C# dictionary examples.

C# Dictionary Examples:

1)

static void Main(string[] args)
{
dict = new Dictionary<string, object>();
Add(“pi”, 3.14);
Console.WriteLine(“pi = ” + GetAnyValue<double>(“pi”));
Console.ReadLine();
}

OUTPUT:

pi = 3.14

What we simply did here was use a different method to assign the value ‘3.14’ to the key, that is, ‘pi’. The keyword Console.ReadLine is used as a function which will prompt us when it tries to retrieve that value of the key from your C# dictionary

2)

static void Main(string[] args)
{
dict = new Dictionary<string, object>();
// in this C# dictionary example, let us presume that we need to make a dictionary of the details of a person; a personal profile, if you will. Beginning with that persons name, we will try to store their name into the key “name”
Add(“name”, “Jane”);
Console.WriteLine(“name = ” + GetAnyValue<string>(“name”));
Console.ReadLine();
}

OUTPUT:

name = Jane

Hopefully, you are getting the hang of it. For the next C# dictionary example, let us see if we can use this C# dictionary like a real-life dictionary written in spoken language instead of a programming script. For additional efficiency in your practice, type out an example on your own, in which you store a value (definition) within a key (word) and the try to compile it to get the result. You may then compare your code with ours to witness the progress that you have made since the beginning of this article.

3)

static void Main(string[] args)
{
dict = new Dictionary<string, object>();
Add(“rare”, “uncommon”);
// Reminder: you may keep on adding values to keys one after the other and the compiler would compile them all together and present the output in a sequence. The code has been repeated since we are portraying different examples, which will also help you in understanding, comprehending and memorising the code much faster and easier.
Console.WriteLine(“rare = ” + GetAnyValue<string>(“rare”));
Console.ReadLine();
}

OUTPUT:

rare = uncommon

4)

static void Main(string[] args)
{
dict = new Dictionary<string, object>();
Add(“k”, “9”);
// since ‘9’ is an integer, you may or may not put it between quotation marks (“”) It does not make a difference with integers.
Console.WriteLine(“k = ” + GetAnyValue<int>(“k”));
Console.ReadLine();
}

OUTPUT:

k = 9

With the 4 C# dictionary examples that we have just reviewed, we have seen how a dictionary is just an object of string data type which has the capability to hold within itself other types, including another string data type. What do you think will happen if you command your program to retrieve a value for a key that does not exist within your C# dictionary? Well, it will simply return the value for the non-existent link to be ‘0’ by default. With this, we come to an end to our C# dictionary tutorial.

As you may have witnessed, using a dictionary in C# is a simple process that lets you store almost any data type within your established dictionary. They are extremely useful for data storage and retrieval and ensure maximum accuracy in terms of ‘what’ (value) is stored ‘where’ (key). As long as you know how to retrieve your data from a defined key in your dictionary, you will be able to use this utility to learn coding in C# much faster.

Do you know?
1. C# Enum
2. C# Dictionary
3. C# Switch Case
4. C# Substring
5. C# Foreach

Pin It on Pinterest