Consider the following C# code snippet:
var dict = new Dictionary<string, int>() { {"apple", 3}, {"banana", 5} };
int value = dict["banana"];
Console.WriteLine(value);What will be printed?
var dict = new Dictionary<string, int>() { {"apple", 3}, {"banana", 5} }; int value = dict["banana"]; Console.WriteLine(value);
Look at the key used to get the value from the dictionary.
The dictionary contains the key "banana" with value 5, so accessing dict["banana"] returns 5.
You want to add a new entry with key "orange" and value 7 to an existing dictionary dict. Which code snippet is correct?
Remember the method name to add a new key-value pair in Dictionary.
The Add method is used to add a new key-value pair. Using the indexer with assignment also works but is not the method call asked here. Insert and Put are not valid Dictionary methods.
Examine this C# code:
var dict = new Dictionary<string, int>(); int value = dict["missingKey"]; Console.WriteLine(value);
What happens when this code runs?
var dict = new Dictionary<string, int>(); int value = dict["missingKey"]; Console.WriteLine(value);
Think about what happens when you access a key that does not exist in a dictionary.
Accessing a missing key with the indexer throws a KeyNotFoundException at runtime.
You want to check if the key "pear" exists in a dictionary and get its value if it does. Which code snippet is the most efficient and safe?
Look for a method that combines checking and retrieving in one call.
TryGetValue checks if the key exists and returns the value in one call without throwing exceptions, making it efficient and safe.
Given an empty dictionary dict of type Dictionary<string, int>, you run these commands:
dict["a"] = 1;
dict["b"] = 2;
dict["a"] = 3;
dict.Add("c", 4);How many key-value pairs does dict contain now?
var dict = new Dictionary<string, int>(); dict["a"] = 1; dict["b"] = 2; dict["a"] = 3; dict.Add("c", 4); int count = dict.Count;
Remember what happens when you assign a value to an existing key.
Assigning to an existing key updates its value without adding a new pair. So keys are "a", "b", and "c" → total 3.