Basics of dictionary in C#

Introduction

In this blog, we will understand the basics of a dictionary in C#. The dictionary is a collection of key-value pairs. When we create a dictionary in C# we need to specify a type for the key and the type for the value. Dictionary class is present in the "System.Collections.Generic" namespace.  The fastest way to find a value within a dictionary is by using its key. The keys within the dictionary must be unique.

Example: Phone Book Dictionary

Imagine you have a phone book, which is like a dictionary in C#. In this phone book, you want to store people's names (keys) along with their phone numbers (values).

Keys: The names of people are the keys. Each name is unique, just like words in a real dictionary.

Values: The phone numbers are the values. Each name (key) is associated with a specific phone number (value).

Here's what it looks like:

"Alice" is a key, and its associated value is her phone number: "555-1234".

"Bob" is another key, and its associated value is his phone number: "555-5678".

"Charlie" is also a key, and its associated value is his phone number: "555-9876".

With this phone book dictionary, if you want to find someone's phone number, you just look up their name (the key), and you can quickly get their phone number (the value). It's a convenient way to store and retrieve information.

In C#, you can create and use dictionaries in your programs to store and retrieve data efficiently. Here's a simple example in C#:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary to store phone numbers.
        Dictionary<string, string> phoneBook = new Dictionary<string, string>();

        // Add entries to the dictionary.
        phoneBook["Alice"] = "555-1234";
        phoneBook["Bob"] = "555-5678";
        phoneBook["Charlie"] = "555-9876";

        // Look up a phone number by name (key).
        string alicePhoneNumber = phoneBook["Alice"];
        Console.WriteLine("Alice's phone number is: " + alicePhoneNumber);
    }
}

In this C# example, we create a dictionary called phoneBook that maps names (keys) to phone numbers (values). We add entries to the dictionary, and then we can quickly look up and retrieve phone numbers by providing the name (key).

So, in C#, a dictionary is a useful tool for storing and managing data where you need to associate one piece of information (the value) with another unique identifier (the key). It's like a phone book for your program!

Comments

Popular posts from this blog

Exploring the Compilation of a C# Program

Difference between static members and instance members

Enforcing Uniqueness in Multiple Fields of a Database Table