// Exercise 1: fix the classic bugs (easy) // // Each method below contains a well-known C# gotcha. Fix them so the checks pass: // - MakeCounters(): the returned functions must return 0, 1, 2 (closure capture in a for loop). // - ApplyDiscount(): must actually change the prices in the list (List of mutable structs). // - TotalPrice(): 0.1 + 0.2 + 0.3 must be exactly 0.6 (use decimal for money). // - Normalize(): must return the trimmed, upper-cased string (strings are immutable). // // Run with: dotnet run (inside a console project). using System; using System.Collections.Generic; using System.Linq; struct PriceTag { public string Sku; public decimal Price; } class Program { static List> MakeCounters() { var list = new List>(); for (int i = 0; i < 3; i++) list.Add(() => i); return list; } static void ApplyDiscount(List tags, decimal factor) { foreach (var t in tags) { var copy = t; copy.Price *= factor; } } static bool TotalIsExact() { double total = 0.1 + 0.2 + 0.3; return total == 0.6; } static string Normalize(string s) { s.Trim(); s.ToUpperInvariant(); return s; } static void Main() { int pass = 0, total = 0; void Check(string name, bool ok) { total++; if (ok) pass++; Console.WriteLine($"{(ok ? "PASS" : "FAIL")}: {name}"); } Check("closures capture per-iteration values", string.Join(",", MakeCounters().Select(f => f())) == "0,1,2"); var tags = new List { new PriceTag { Sku = "a", Price = 10m }, new PriceTag { Sku = "b", Price = 20m } }; ApplyDiscount(tags, 0.5m); Check("struct elements updated", tags[0].Price == 5m && tags[1].Price == 10m); Check("decimal arithmetic is exact", TotalIsExact()); Check("strings are immutable", Normalize(" hello ") == "HELLO"); Console.WriteLine($"--- {pass}/{total} checks passed ---"); } }