Problem overview
A shopper can type a coupon code at checkout. The program keeps a Dictionary<string, int> named coupons that maps each valid code to the amount it takes off: SAVE10 is 10, SAVE20 is 20 and SAVE50 is 50. Given a subtotal and the typed coupon, the program prints the total after the discount.
With a subtotal of 100 and the code SAVE20, the discount is 20 and the output is:
Total: $80
If the code isn't in the dictionary, nothing is taken off. With the same subtotal and the code FREE, the output is Total: $100.
Approach: look the code up, with a default
A dictionary stores pairs: a key (the coupon text) and a value (the discount). Asking for the value of a key is a direct lookup, with no need to scan every coupon. The difficulty is the case where the shopper types a code that doesn't exist. In C#, reading a missing key with the indexer doesn't return a default value, it throws an exception. So the program checks first whether the key is there, and uses 0 as the discount when it isn't.
Once the discount is known, the rest is simple arithmetic and text: total = subtotal - discount, then the text Total: $ followed by the total.
Step by step
- Find the discount.
coupons.ContainsKey(coupon)is true when the code is a key. Use it as the condition of a ternary: the valuecoupons[coupon]when it is true,0when it is false. - Compute the total as
subtotal - discount. - Build the text.
resultis"Total: $"joined withtotalby+. - Print
resultwithConsole.WriteLine.
The solution in C#
int subtotal = 100;
string coupon = "SAVE20";
Dictionary<string, int> coupons = new Dictionary<string, int>();
coupons["SAVE10"] = 10;
coupons["SAVE20"] = 20;
coupons["SAVE50"] = 50;
int discount = coupons.ContainsKey(coupon) ? coupons[coupon] : 0;
int total = subtotal - discount;
string result = "Total: $" + total;
Console.WriteLine(result);
The C# details worth a closer look:
- Setting a value with the indexer.
coupons["SAVE10"] = 10;adds the key if it is new and replaces the value if the key exists.coupons.Add("SAVE10", 10)behaves differently: calling it with a key that is already present throws anArgumentException. - Reading a missing key throws.
coupons["FREE"]throws aKeyNotFoundExceptionwith the message The given key 'FREE' was not present in the dictionary. That is why the lookup is guarded byContainsKey. In the ternary,coupons[coupon]is only evaluated when the condition is true. - The ternary.
condition ? a : bgivesaif the condition is true andbotherwise. Both branches here areint, so the whole expression is anint. - Two shorter forms.
TryGetValuedoes the check and the read in one lookup:coupons.TryGetValue(coupon, out int found) ? found : 0. Andcoupons.GetValueOrDefault(coupon)returns the default of the value type when the key is missing, which is 0 forint. Both give the same results as the lesson's version: 20 forSAVE20and 0 for an unknown code. The lesson's two-step form is the most explicit. - The dictionary type.
Dictionary<string, int>is inSystem.Collections.Generic. The first type argument is the key type and the second is the value type.
Edge cases and common mistakes
- An unknown code.
"FREE"isn't a key, so the discount is 0 and the total equals the subtotal:Total: $100. - Case matters. Keys are compared exactly, so
"save20"is not"SAVE20". With a lowercase code the discount is 0 and the output isTotal: $100. - A
nullcode. A dictionary doesn't acceptnullas a key to look up.ContainsKey(null)throws anArgumentNullException. The lesson's code is always a text, so there is nothing to guard against. - A discount bigger than the subtotal. Nothing in the code limits the total to zero. With a subtotal of 30 and
SAVE50, the output isTotal: $-20. A real checkout would need a rule for this case, which this lesson doesn't ask for. - Indexing without the check.
int discount = coupons[coupon];works for the three known codes and throws for any other. - Adding the discount. The total is the subtotal minus the discount. Adding it would raise the price:
SAVE20would give 120.
Testing
- Subtotal 100 with
"SAVE20"givesTotal: $80. - Subtotal 100 with
"SAVE50"givesTotal: $50. - Subtotal 100 with
"FREE"givesTotal: $100. - Subtotal 100 with
"save20"givesTotal: $100. - Subtotal 30 with
"SAVE50"givesTotal: $-20.
