Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson11 / 20

    Module 3 · Collections and objects: organise your data · Lesson 11 of 20

    Find a value by name with a dictionary

    How many minutes belong to Monday—and what if Monday has no entry? A lookup by name needs a clear missing-key path.

    An array or list answers a position question: what is at index 0? A dictionary answers a name question: what value belongs to Monday? In Dictionary<string, int>, each key is a string and each value is an int. The type names inside angle brackets tell C# what this collection accepts. A key identifies one entry; different keys may have equal values.

    Predict before running

    Write the three output lines before running this complete program. It changes the existing Monday entry and asks about a different day.

    C#
    using System;
    using System.Collections.Generic;
    
    Dictionary<string, int> minutesByDay = new Dictionary<string, int>();
    minutesByDay.Add("Monday", 20);
    minutesByDay["Monday"] = 35;
    
    if (minutesByDay.TryGetValue("Tuesday", out int minutes))
    {
        Console.WriteLine($"Tuesday: {minutes}");
    }
    else
    {
        Console.WriteLine("No Tuesday session.");
    }
    
    Console.WriteLine($"Monday: {minutesByDay["Monday"]}");
    Console.WriteLine($"Entries: {minutesByDay.Count}");

    What are the three output lines?

    A No Tuesday session.; Monday: 35; Entries: 1
    B Tuesday: 0; Monday: 35; Entries: 2
    C No Tuesday session.; Monday: 20; Entries: 1
    D The program cannot use a string key.
    Show answer

    Correct answer: A

    Tuesday was never added. Assigning through the existing Monday key replaces its value and leaves the count at one.

    Option B: A missing lookup does not add an entry. The if branch is skipped when TryGetValue returns false.

    Option C: The indexer assignment changed Monday from 20 to 35.

    Option D: The dictionary was declared with string keys.

    Hint: Track the set of keys separately from their values.

    Draw keys and values separately

    Text
    minutesByDay
      key          value
      "Monday" --> 35
    
    lookup "Tuesday" --> not found
    Count = 1

    Add means add a new key. Assigning through minutesByDay["Monday"] means set the value for that key; it also adds a new entry if that key is missing. Reading an indexer for a missing key throws an exception. For a lookup that may reasonably be missing, use TryGetValue: its bool result tells you whether the key was found, and its out variable receives the value. Use the value inside the successful branch.

    Monday already exists. What happens if minutesByDay.Add("Monday", 50) runs?

    A It silently replaces Monday with 50.
    B It creates a second Monday entry.
    C It throws an ArgumentException.
    D It removes Monday.
    Show answer

    Correct answer: C

    Add requires a new key. An already present key causes an ArgumentException; lesson 14 explains exception handling.

    Option A: Assignment through the indexer replaces a value; Add does not.

    Option B: A dictionary cannot hold duplicate keys according to its key comparison rule.

    Option D: Add is not a removal operation.

    Hint: Choose Add when duplication should be treated as a mistake; choose assignment when replacing is intended.

    Your turn: a useful lookup

    Read the condition before coding: day != null means the input is not null. && means both conditions must be true. It checks the left side first and skips the right side when the left side is false. This short-circuit behaviour prevents a lookup with a null key.

    Build a lookup with Monday = 25 and Tuesday = 0. Ask for a day name. A recorded zero must print zero; an absent day must say there is no entry. Write an attempt first, then compare it with this complete solution. Enter the day names exactly as shown; this dictionary uses its default case-sensitive string matching.

    C#
    using System;
    using System.Collections.Generic;
    
    Dictionary<string, int> minutesByDay = new Dictionary<string, int>();
    minutesByDay.Add("Monday", 25);
    minutesByDay.Add("Tuesday", 0);
    
    Console.WriteLine("Day name:");
    string? day = Console.ReadLine();
    if (day != null && minutesByDay.TryGetValue(day, out int minutes))
    {
        Console.WriteLine($"Recorded minutes: {minutes}");
    }
    else
    {
        Console.WriteLine("No entry for that day.");
    }

    Run it with Monday, Tuesday and Wednesday. Expect respectively Recorded minutes: 25, Recorded minutes: 0, and No entry for that day after the prompt. An empty line or end of input also takes the missing-entry path. The null check prevents passing a null key.

    Tuesday has a stored value of 0. Which result proves a key is absent?

    A The returned int is 0.
    B TryGetValue returns false.
    C The dictionary contains at least one entry.
    D The key is a string.
    Show answer

    Correct answer: B

    A zero can be real stored data. The bool returned by TryGetValue distinguishes found from missing.

    Option A: A present key can legitimately store zero.

    Option C: Count does not tell you whether this particular key exists.

    Option D: The type of the key does not prove presence.

    Explain it back

    Explain why a list index and a dictionary key solve different problems. Then explain why testing only whether minutes equals zero loses information. Before continuing, change the values, keep one stored zero, and test one absent day again. Keep the key name and stored value in separate columns in your trace so you can see which detail changed.

    References: Microsoft - Dictionary and TryGetValue.

    Quick reference

    • Dictionary<TKey, TValue> maps unique keys to values.
    • Add requires a new key.
    • Indexer assignment sets or replaces a value.
    • Use TryGetValue when a key may be absent.
    • Its bool result distinguishes missing from a stored zero.
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·