Recall & Review
beginner
What is the purpose of the
ContainsKey method in a C# Dictionary?The
ContainsKey method checks if a specific key exists in the dictionary. It returns true if the key is found, otherwise false.Click to reveal answer
beginner
How do you safely retrieve a value from a Dictionary without risking an exception if the key is missing?
Use the
TryGetValue method. It attempts to get the value for a key and returns true if successful, otherwise false. This avoids exceptions if the key is not present.Click to reveal answer
beginner
What happens if you try to access a Dictionary value using a key that does not exist with the indexer syntax (e.g.,
dict[key])?Accessing a non-existent key with the indexer throws a
KeyNotFoundException. To avoid this, use TryGetValue or check with ContainsKey first.Click to reveal answer
beginner
Which Dictionary method removes a key and its associated value?
The
Remove method deletes the key-value pair from the dictionary. It returns true if the key was found and removed, otherwise false.Click to reveal answer
beginner
How can you iterate over all keys and values in a Dictionary?
Use a
foreach loop over the dictionary. Each item is a KeyValuePair<TKey, TValue> where you can access Key and Value properties.Click to reveal answer
Which method checks if a key exists in a C# Dictionary?
✗ Incorrect
The
ContainsKey method returns true if the key exists in the dictionary.What does
TryGetValue return if the key is not found?✗ Incorrect
TryGetValue returns false if the key is missing, avoiding exceptions.What exception is thrown when accessing a missing key with
dict[key]?✗ Incorrect
Accessing a missing key with the indexer throws a
KeyNotFoundException.Which method removes a key-value pair from a Dictionary?
✗ Incorrect
Remove deletes the key and its value from the dictionary.How do you access the key and value inside a foreach loop over a Dictionary?
✗ Incorrect
Each item is a KeyValuePair where you use
Key and Value properties.Explain how to safely get a value from a Dictionary when you are not sure if the key exists.
Think about a method that returns true or false and gives you the value if it exists.
You got /4 concepts.
Describe how to remove an item from a Dictionary and how to check if the removal was successful.
Focus on the method that deletes a key-value pair and what it returns.
You got /4 concepts.