c-sharp
  1. c-sharp-dictionary

C# Dictionary

In C#, a Dictionary is a collection type that allows you to store key-value pairs. Each key in the dictionary maps to a specific value. Dictionaries are used to quickly access values based on their keys, which can be useful for many scenarios. In this tutorial, we'll discuss how to use dictionaries in C#.

Syntax

The syntax for creating a dictionary in C# is as follows:

Dictionary<TKey, TValue> myDictionary = new Dictionary<TKey, TValue>();

Replace "TKey" and "TValue" with the types you want to use as the key and value, respectively.

You can add key-value pairs to the dictionary like this:

myDictionary.Add(key, value);

You can retrieve a value from the dictionary like this:

TValue value = myDictionary[key];

Example

Let's create a dictionary that maps the names of different programming languages to their corresponding creator. Here's how we can implement it:

Dictionary<string, string> creators = new Dictionary<string, string>();
creators.Add("Java", "James Gosling");
creators.Add("C#", "Microsoft");
creators.Add("Python", "Guido van Rossum");

Now, we can retrieve a creator by the name of the language:

string creator = creators["C#"];
Console.WriteLine(creator); // Output: Microsoft

Output

When we run the example code above, the output will be:

Microsoft

This is because we retrieved the value associated with the key "C#" in the "creators" dictionary, which is "Microsoft".

Explanation

In the example above, we created a dictionary called "creators" that maps the names of different programming languages to their corresponding creator. We then added key-value pairs to the dictionary and retrieved a creator based on the name of the language.

Use

Dictionaries are useful when you need to associate values with specific keys. They are commonly used to store settings, configuration values, lookup tables, and other collections of key-value pairs.

Important Points

  • Each key in a dictionary must be unique.
  • You can use the ContainsKey method to check if a key exists in the dictionary.
  • You can iterate over the key-value pairs in the dictionary using a foreach loop or the KeyValuePair struct.
  • You can use the TryGetValue method to retrieve a value from the dictionary without throwing an exception if the key doesn't exist.

Summary

In this tutorial, we discussed how to use dictionaries in C#. We covered the syntax, example, output, explanation, use, and important points of dictionaries in C#. With this knowledge, you can now use dictionaries in your C# code to store key-value pairs and quickly access the values based on their keys.

Published on: