var moves = "NNEuEuuS"; var here = new Spot { X = 0, Y = 0 }; var history = new Stack(); foreach (char move in moves) { if (move == 'u') { if (history.Count > 0) { here = history.Pop(); } } else { history.Push(here); switch (move) { case 'N': here.Y += 1; break; case 'S': here.Y -= 1; break; case 'E': here.X += 1; break; case 'W': here.X -= 1; break; } } Console.WriteLine($"{move} at {here} history: {string.Join(" ", history)}"); } struct Spot { public int X; public int Y; public override string ToString() => $"({X},{Y})"; } // Try this next… // // 1. Change `struct Spot` to `class Spot` and save. Every entry in the history // turns into the current spot, and undo stops working. Before you look, // predict which line goes wrong first. // // 2. Keep `class Spot` and make undo work again by changing one line: push a // fresh object, `new Spot { X = here.X, Y = here.Y }`, instead of `here`. // You have written by hand the copy that a struct makes for free. // // 3. Now try `record class Spot(int X, int Y)`: start with `new Spot(0, 0)` // and move with `here = here with { Y = here.Y + 1 };`. It's a class again, // and undo still works. Why? Nothing ever changes a Spot after it is made, // so sharing one is safe. // // 4. Add a `List Notes` field to the struct and add a note on every // move. Undo the moves. Do the notes come back too? Copying a struct copies // the reference to the list, not the list. // // 5. After each move, print `history.Peek() == here` with the struct, then // with a record class. The struct version won't compile until you write `==` // yourself; the record wrote one for you. What does each one compare? // // 6. Move the switch into a function, `void Step(Spot s, char move)`, and call // it. Does `here` still move? Then write `ref Spot s` and `Step(ref here, move)` // and try again, once with the struct and once with the class.