Dictionary in C#

Dictionary in C# is a collection of keys and values.

To use dictionaries we need to import System.Collections.Generic namespace.

The example:

using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var books = new Dictionary<string, int>();
        books.Add("Harry Potter", 3);

        Console.WriteLine(books["Harry Potter"]);
    }
}
Firstly, we define a new variable called books and instantiate it using dictionary constructor.

We choose the string and integer as our parameters for the generic class input.

This means that this dictionary will contain keys of type string and values of type integer.

We use the Add method to add new Key/Value pair into the dictionary.

We can use the brackets ([]) and use the key to get acces to the value.

The result:

3