// Exercise 2: a value object with records and validation (easy) // // Implement Money as a record with: // - A constructor that rejects negative amounts and currencies that aren't 3 uppercase letters // (throw ArgumentException). // - Add(Money other): returns a new Money; throws InvalidOperationException for different currencies. // - Allocate(int parts): splits the amount into `parts` Money values in cents that differ by at most 0.01 // and sum exactly to the original (e.g. 10.00 / 3 → 3.34, 3.33, 3.33). Larger parts first. // - Value equality and ToString " " (e.g. "10.00 EUR"), formatted with the invariant culture. // // Run with: dotnet run (inside a console project). using System; using System.Linq; record Money { public decimal Amount { get; } public string Currency { get; } public Money(decimal amount, string currency) { Amount = amount; Currency = currency; // TODO: validate } public Money Add(Money other) => this; // TODO public Money[] Allocate(int parts) => new Money[0]; // TODO public override string ToString() => ""; // TODO } class Program { static void Main() { int pass = 0, total = 0; void Check(string name, bool ok) { total++; if (ok) pass++; Console.WriteLine($"{(ok ? "PASS" : "FAIL")}: {name}"); } bool Throws(Action a) where T : Exception { try { a(); return false; } catch (T) { return true; } } Check("rejects negative", Throws(() => new Money(-1m, "EUR"))); Check("rejects bad currency", Throws(() => new Money(1m, "eur")) && Throws(() => new Money(1m, "EURO"))); Check("value equality", new Money(5m, "EUR") == new Money(5.00m, "EUR")); Check("add", new Money(2.5m, "EUR").Add(new Money(1.25m, "EUR")) == new Money(3.75m, "EUR")); Check("currency mismatch", Throws(() => new Money(1m, "EUR").Add(new Money(1m, "USD")))); var parts = new Money(10m, "EUR").Allocate(3); Check("allocate " + string.Join(" | ", parts.Select(p => p.ToString())), parts.Select(p => p.Amount).SequenceEqual(new[] { 3.34m, 3.33m, 3.33m }) && parts.Sum(p => p.Amount) == 10m); Check("ToString", new Money(10m, "EUR").ToString() == "10.00 EUR"); Console.WriteLine($"--- {pass}/{total} checks passed ---"); } }