Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Dictionary methods and access patterns in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Dictionary methods and access patterns
Create Dictionary
Add Key-Value Pairs
Access Value by Key
Key Exists?
NoHandle Missing Key
Use Value
Use Dictionary Methods
Update or Remove Entries
End
Start by creating a dictionary and adding pairs. Access values by keys, checking if keys exist. Use dictionary methods to update or remove entries.
Execution Sample
C Sharp (C#)
var dict = new Dictionary<string, int>();
dict["apple"] = 3;
int count = dict["apple"];
bool hasKey = dict.ContainsKey("banana");
Create a dictionary, add an entry, access a value, and check if a key exists.
Execution Table
StepActionDictionary StateResult/Output
1Create empty dictionary{}Dictionary created, empty
2Add key "apple" with value 3{"apple":3}Entry added
3Access value for key "apple"{"apple":3}3
4Check if key "banana" exists{"apple":3}False
5Try to access value for key "banana" (not shown in code, but common pattern){"apple":3}KeyNotFoundException if accessed directly
6Use ContainsKey before access to avoid exception{"apple":3}Safe check returns False
7End of operations{"apple":3}Execution stops
💡 No more operations; dictionary remains with one entry
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
dict{}{"apple":3}{"apple":3}{"apple":3}{"apple":3}
countundefinedundefined333
hasKeyundefinedundefinedundefinedFalseFalse
Key Moments - 2 Insights
Why do we check ContainsKey before accessing a key?
Because accessing a key that does not exist causes an exception. Checking ContainsKey (see step 4 and 6) prevents this error by confirming the key is present.
What happens if we try to access a key that is not in the dictionary?
The program throws a KeyNotFoundException (step 5). To avoid this, use ContainsKey or TryGetValue methods.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'count' after step 3?
A3
Bundefined
C0
DKeyNotFoundException
💡 Hint
Check the 'count' variable in variable_tracker after step 3
At which step does the dictionary contain the key "apple"?
AStep 1
BStep 2
CStep 4
DStep 5
💡 Hint
Look at the dictionary state column in execution_table at step 2
If we try to access dict["banana"] without checking ContainsKey, what happens?
AReturns 0
BReturns null
CThrows KeyNotFoundException
DAdds "banana" with default value
💡 Hint
See step 5 in execution_table for what happens when accessing a missing key
Concept Snapshot
Dictionary methods and access patterns in C#:
- Create with: var dict = new Dictionary<TKey, TValue>();
- Add/update: dict[key] = value;
- Access: dict[key] (throws if key missing)
- Check key: dict.ContainsKey(key)
- Use TryGetValue for safe access
- Remove with dict.Remove(key)
Full Transcript
This example shows how to create a dictionary in C#, add a key-value pair, access a value by key, and check if a key exists. We start with an empty dictionary, add "apple" with value 3, then read that value into a variable. We check if "banana" exists, which it does not. Accessing a missing key directly causes an exception, so we use ContainsKey to avoid errors. Variables track the dictionary state and values step-by-step.

Practice

(1/5)
1. What does the ContainsKey method do in a C# Dictionary?
easy
A. Checks if a specific key exists in the dictionary
B. Adds a new key-value pair to the dictionary
C. Removes a key and its value from the dictionary
D. Returns the number of items in the dictionary

Solution

  1. Step 1: Understand the purpose of ContainsKey

    The ContainsKey method checks if a given key is present in the dictionary.
  2. Step 2: Compare with other dictionary methods

    Add adds items, Remove deletes items, and Count returns the number of items, so these are different from ContainsKey.
  3. Final Answer:

    Checks if a specific key exists in the dictionary -> Option A
  4. Quick Check:

    ContainsKey checks key presence [OK]
Hint: ContainsKey checks if key exists before access [OK]
Common Mistakes:
  • Confusing ContainsKey with Add method
  • Thinking ContainsKey returns a value instead of a boolean
  • Mixing ContainsKey with Count property
2. Which of the following is the correct way to add a key-value pair to a Dictionary<string, int> named ages?
easy
A. ages.Add("Alice", 30);
B. ages.Add["Alice"] = 30;
C. ages["Alice"].Add(30);
D. ages.Insert("Alice", 30);

Solution

  1. Step 1: Recall the syntax for adding items to Dictionary

    The correct method to add a key-value pair is Add(key, value).
  2. Step 2: Check each option's syntax

    ages.Add("Alice", 30); uses Add("Alice", 30) which is correct. ages.Add["Alice"] = 30; uses square brackets with Add which is invalid. ages["Alice"].Add(30); tries to call Add on the value, which is wrong. ages.Insert("Alice", 30); uses Insert which does not exist for Dictionary.
  3. Final Answer:

    ages.Add("Alice", 30); -> Option A
  4. Quick Check:

    Add(key, value) syntax [OK]
Hint: Use Add(key, value) to insert new pairs [OK]
Common Mistakes:
  • Using square brackets with Add method
  • Trying to call Add on a value instead of dictionary
  • Using Insert method which does not exist
3. What will be the output of this code?
var dict = new Dictionary<string, int>();
dict.Add("x", 10);
dict["y"] = 20;
Console.WriteLine(dict["x"] + dict["y"]);
medium
A. 10 20
B. 30
C. x y
D. Runtime error

Solution

  1. Step 1: Understand dictionary additions

    First, dict.Add("x", 10) adds key "x" with value 10. Then dict["y"] = 20 adds key "y" with value 20.
  2. Step 2: Calculate the sum printed

    dict["x"] is 10 and dict["y"] is 20, so their sum is 30.
  3. Final Answer:

    30 -> Option B
  4. Quick Check:

    10 + 20 = 30 [OK]
Hint: Sum values accessed by keys with dict[key] syntax [OK]
Common Mistakes:
  • Expecting output as separate values instead of sum
  • Confusing keys and values in output
  • Thinking dict["y"] is invalid without Add
4. Identify the error in this code snippet:
var dict = new Dictionary<string, int>();
dict.Add("a", 1);
dict.Add("a", 2);
Console.WriteLine(dict["a"]);
medium
A. Key "a" will be removed automatically
B. Compilation error due to missing semicolon
C. Duplicate key exception on second Add call
D. Output will be 2 without error

Solution

  1. Step 1: Understand Add method behavior with duplicate keys

    The Add method throws an exception if the key already exists.
  2. Step 2: Analyze the code flow

    The first Add("a", 1) works fine. The second Add("a", 2) tries to add the same key again, causing an exception.
  3. Final Answer:

    Duplicate key exception on second Add call -> Option C
  4. Quick Check:

    Adding duplicate key throws exception [OK]
Hint: Add throws error if key exists; use indexer to overwrite [OK]
Common Mistakes:
  • Assuming Add overwrites existing keys
  • Expecting no error and value updated
  • Confusing Add with indexer assignment
5. Given a dictionary scores with student names as keys and their scores as values, which code snippet safely retrieves the score for "John" without causing an error if the key is missing?
hard
A. int score = scores.ContainsKey("John");
B. int score = scores.GetValueOrDefault("John");
C. int score = scores["John"];
D. scores.TryGetValue("John", out int score);

Solution

  1. Step 1: Understand safe retrieval methods

    Using TryGetValue safely tries to get the value and returns false if key is missing without error.
  2. Step 2: Analyze each option

    int score = scores["John"]; throws an exception if "John" is missing. int score = scores.GetValueOrDefault("John"); is invalid in C# Dictionary (GetValueOrDefault is not standard). scores.TryGetValue("John", out int score); uses TryGetValue correctly. int score = scores.ContainsKey("John"); returns a boolean, not the score.
  3. Final Answer:

    scores.TryGetValue("John", out int score); -> Option D
  4. Quick Check:

    TryGetValue safely gets value [OK]
Hint: Use TryGetValue to avoid errors on missing keys [OK]
Common Mistakes:
  • Using indexer without checking key existence
  • Confusing ContainsKey with value retrieval
  • Expecting GetValueOrDefault method on Dictionary