Skip to main content

Practice · 2 of 3

Defensive copies in readonly members

CHALLENGE
Difficulty: advanced+25 XP

A mutable struct stored in a readonly field is copied on every member access. Implement struct Container with private readonly Mut _m; and a public int Get() that reads _m.Value twice and returns their sum. Implement struct Mut { public int Value; }. The lesson: each _m.Value read copies first — implement it so the TEST (which checks the sum) passes; you cannot observe the copies from outside, which is exactly the point: they are invisible but real.

Back to lesson: Practice: Memory drills