Thuta Learning
C#
AdvancedProgrammingBeginner

Collections (Dictionary)

C#Lesson 2525 min

What you'll walk away with

  • Explain the core concept and runtime behavior of Collections (Dictionary)
  • Test normal, boundary, and invalid cases independently
  • Write readable, type-safe, and testable C# code

Explain it simply

Collections (Dictionary), in plain language

Dictionary<TKey, TValue> is a collection that stores data as key-value pairs. Because keys and values are paired together, it's great for mapping data like username to role, product code to price, or country to capital.

Problem → Why → Solution

The problem — why this concept matters

Reading an unknown key directly through the indexer causes `KeyNotFoundException`.

A common mistake

Assuming one successful happy path proves the code is correct, maintainable, and production-ready.

Core concept — understand how it works

`Dictionary<TKey,TValue>` maps unique keys to values and depends on equality comparers and correct hash codes. Handle missing keys, duplicate insertion, case sensitivity, and mutable keys deliberately.

Mental model
  1. task or collection
  2. .NET API and pipeline
  3. typed result or failure

Explain the core concept and runtime behavior of Collections (Dictionary)

Core syntax or pattern

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> productPrices = new Dictionary<string, int>();

        productPrices.Add("Laptop", 1200);
        productPrices.Add("Mouse", 25);
        productPrices.Add("Keyboard", 80);

        Console.WriteLine(productPrices["Laptop"]);

        if (productPrices.ContainsKey("Mouse"))
        {
            Console.WriteLine($"Mouse price: {productPrices["Mouse"]}");
        }
    }
}

`Dictionary<TKey,TValue>` maps unique keys to values and depends on equality comparers and correct hash codes. Handle missing keys, duplicate insertion, case sensitivity, and mutable keys deliberately.

Read the code step by step

  1. task or collectionusing System;

    Dictionary<TKey, TValue> is a collection that stores data as key-value pairs. Because keys and values are paired together, it's great for mapping data like username to role, product code to price, or country to capital.

  2. .NET API and pipelineproductPrices.Add("Mouse", 25);

    `Dictionary<TKey,TValue>` maps unique keys to values and depends on equality comparers and correct hash codes. Handle missing keys, duplicate insertion, case sensitivity, and mutable keys deliberately.

  3. typed result or failure}

    Build a case-insensitive email dictionary with `StringComparer.OrdinalIgnoreCase`, testing `TryGetValue` and duplicate policy.

Execution flow
  1. task or collection
  2. .NET API and pipeline
  3. typed result or failure

Success

Explain the core concept and runtime behavior of Collections (Dictionary)

Failure

Reading an unknown key directly through the indexer causes `KeyNotFoundException`.

Dictionary<TKey, TValue> is a collection that stores data as key-value pairs. Because keys and values are paired together, it's great for mapping data like username to role, product code to price, or country to capital.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> productPrices = new Dictionary<string, int>();

        productPrices.Add("Laptop", 1200);
        productPrices.Add("Mouse", 25);
        productPrices.Add("Keyboard", 80);

        Console.WriteLine(productPrices["Laptop"]);

        if (productPrices.ContainsKey("Mouse"))
        {
            Console.WriteLine($"Mouse price: {productPrices["Mouse"]}");
        }
    }
}

Watch out for this

  • productPrices["Laptop"] uses the key to fetch the value.
  • Accessing a key that doesn't exist can throw an error. That's why it's safer to check first with ContainsKey().
  • Dictionary keys must be unique. Adding a duplicate key can cause an error.
You should see
1200 Mouse price: 25

Real-world usage

How to apply it in a real project

Build a case-insensitive email dictionary with `StringComparer.OrdinalIgnoreCase`, testing `TryGetValue` and duplicate policy.

Mini challenge

Build it yourself

Build a case-insensitive email dictionary with `StringComparer.OrdinalIgnoreCase`, testing `TryGetValue` and duplicate policy.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> productPrices = new Dictionary<string, int>();

        productPrices.Add("Laptop", 1200);
        productPrices.Add("Mouse", 25);
        productPrices.Add("Keyboard", 80);

        Console.WriteLine(productPrices["Laptop"]);

        if (productPrices.ContainsKey("Mouse"))
        {
            Console.WriteLine($"Mouse price: {productPrices["Mouse"]}");
        }
    }
}

Expected: Explain the core concept and runtime behavior of Collections (Dictionary)

Show hint

Build a case-insensitive email dictionary with `StringComparer.OrdinalIgnoreCase`, testing `TryGetValue` and duplicate policy.

Quick quiz 1 / 3

What best describes the core idea of Collections (Dictionary)?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • task or collection → .NET API and pipeline → typed result or failure
  • `Dictionary<TKey,TValue>` maps unique keys to values and depends on equality comparers and correct hash codes. Handle missing keys, duplicate insertion, case sensitivity, and mutable keys deliberately.
  • Reading an unknown key directly through the indexer causes `KeyNotFoundException`.
  • Build a case-insensitive email dictionary with `StringComparer.OrdinalIgnoreCase`, testing `TryGetValue` and duplicate policy.

Collections and data structures — Microsoft Learn

Easy traps

  • Reading an unknown key directly through the indexer causes `KeyNotFoundException`.
  • Assuming one successful happy path proves the code is correct, maintainable, and production-ready.

Hands-on Exercise

Build a case-insensitive email dictionary with `StringComparer.OrdinalIgnoreCase`, testing `TryGetValue` and duplicate policy.

You'll know it worked when: 1200 Mouse price: 25

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Collections (Dictionary) | Thuta Learning