CodeBlanks Logo Icon CodeBlanks

Dictionary<K,V> in depth

C# course · Intermediate · Lesson 77/116

Learn Dictionary<K,V>'s hashing and collision behavior.

Dictionary<K,V> in depth

A Dictionary<K,V> places keys into a bucket array. Each key's GetHashCode() yields a bucket index; keys landing in the same bucket form a chained list.

When two different keys fall into the same bucket it is called a collision. Collisions are normal; inside the chain the key is compared with Equals. A good hash function reduces collisions and keeps lookups fast.

Add, indexer and TryGetValue

The Add method inserts a new key-value pair; if the key exists it throws ArgumentException. Writing prices["apple"] = 5 overwrites an existing value without error.

To check whether a key exists use ContainsKey or TryGetValue. TryGetValue checks presence and returns the value in one pass; it does not search twice.

Exercise Look up a value with TryGetValue

The prices dictionary below is ready. Use TryGetValue to look up "apple"; if found, print the value with Console.WriteLine.

Show example solution
Declare int value; call TryGetValue, and when it returns true print value.
Example solution:
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var prices = new Dictionary<string, int>();
        prices.Add("apple", 5);
        prices.Add("pear", 3);
        int value;
        if (prices.TryGetValue("apple", out value))
        {
            Console.WriteLine(value);
        }
    }
}

Test yourself

  1. Complete the TryGetValue call

    prices.TryGetValue("elma", out____);
    Show answer
    prices.TryGetValue("elma", outint value);
  2. What if you Add an existing key?

    • Value is updated
    • An exception is thrown
    • It is ignored
    • It is overwritten
    Show answer

    An exception is thrown — Correct. Add throws ArgumentException on a duplicate key.

  3. Match the method to its behavior

    TryGetValue
    Returns value if found
    ContainsKey
    Checks key presence
    Add
    Throws on duplicate
    [] indexer
    Overwrites value

All lessons in Intermediate