0
0
C Sharp (C#)programming~20 mins

Dictionary key-value collection in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Dictionary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output of this C# dictionary lookup?

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?

C Sharp (C#)
var dict = new Dictionary<string, int>() { {"apple", 3}, {"banana", 5} };
int value = dict["banana"];
Console.WriteLine(value);
A5
BKeyNotFoundException
C0
D3
Attempts:
2 left
💡 Hint

Look at the key used to get the value from the dictionary.

📝 Syntax
intermediate
2:00remaining
Which option correctly adds a new key-value pair to a C# dictionary?

You want to add a new entry with key "orange" and value 7 to an existing dictionary dict. Which code snippet is correct?

Adict.Add("orange", 7);
Bdict["orange"] = 7;
Cdict.Insert("orange", 7);
Ddict.Put("orange", 7);
Attempts:
2 left
💡 Hint

Remember the method name to add a new key-value pair in Dictionary.

🔧 Debug
advanced
2:00remaining
What error does this code raise?

Examine this C# code:

var dict = new Dictionary<string, int>();
int value = dict["missingKey"];
Console.WriteLine(value);

What happens when this code runs?

C Sharp (C#)
var dict = new Dictionary<string, int>();
int value = dict["missingKey"];
Console.WriteLine(value);
APrints 0
BThrows KeyNotFoundException
CPrints null
DCompilation error
Attempts:
2 left
💡 Hint

Think about what happens when you access a key that does not exist in a dictionary.

optimization
advanced
2:00remaining
Which approach is best to check if a key exists and get its value in C# dictionary?

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?

Aif (dict.ContainsKey("pear")) { var val = dict["pear"]; }
Bvar val = dict["pear"]; if (val != null) { /* use val */ }
Cdict.TryGetValue("pear", out var val);
Dvar val = dict.GetValueOrDefault("pear");
Attempts:
2 left
💡 Hint

Look for a method that combines checking and retrieving in one call.

🧠 Conceptual
expert
2:00remaining
What is the count of items after this sequence?

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?

C Sharp (C#)
var dict = new Dictionary<string, int>();
dict["a"] = 1;
dict["b"] = 2;
dict["a"] = 3;
dict.Add("c", 4);
int count = dict.Count;
AThrows exception
B4
C2
D3
Attempts:
2 left
💡 Hint

Remember what happens when you assign a value to an existing key.