TL ; DR:
d.GetValueOrDefault(key, 0) gives the key's value, or 0 when the key is missing.
Dictionary<string, int> points = new Dictionary<string, int>();
points["Ana"] = 7;
Console.WriteLine(points.GetValueOrDefault("Ana", 0)); // 7
Console.WriteLine(points.GetValueOrDefault("Ben", 0)); // 0
Full lesson:
A missing key often means "none yet". A player with no points yet has 0 points.
points["Ben"] can't say that. It throws a KeyNotFoundException.
GetValueOrDefault takes a key and a default. It gives the key's value when the key is there. It gives the default when it isn't.
Reading this way doesn't add the key. points still has one key afterwards.
It does what this if with ContainsKey does, in one line:
int score = 0;
if (points.ContainsKey("Ben")) {
score = points["Ben"];
}
Your task
stock counts the fruit in a shop. The code reads and prints the pears.
There are no plums yet. Read "plums" with GetValueOrDefault and 0 as the default. Store it in an int named plums.
Then print the plums line, the same way as the pears line.
Expected output:
We have 2 pears
We have 0 plumsFree plan: 30 tutor messages. PRO is unlimited.
