skip to content

In C#, a mutable Counter struct is assigned to an IIncrement interface variable; why does calling Increment through that variable leave the struct unchanged?

level: middleimportance: should knowfreq 45%

answer

  1. interfaces are reference types
  2. the conversion made a copy
  3. the box changes, not the local
  4. casting back copies again
  5. a generic ref call reaches the original

basics

~20 s

Converting a struct to an interface type boxes it, so the interface variable refers to a heap copy. Increment mutates that boxed copy; the original local never changes, and casting the box back to Counter yields yet another copy.

solid answer

~40 s

Boxing applies to interface conversions exactly as it does to `object`: `IIncrement viaInterface = counter;` allocates a box holding a copy of `counter`. Calls through `viaInterface` do mutate state, but the box's state: `((Counter)viaInterface).Hits` reads 2 while `counter.Hits` stays 0. The reverse trap is `((Counter)boxed).Increment()`, which unboxes into a hidden temporary and mutates that, leaving the box unchanged. To mutate the original through the interface's contract without boxing, call through a type parameter, `Bump<T>(ref T item) where T : IIncrement`, which the compiler emits as a constrained call on the variable itself. The simplest prevention is to keep structs that implement interfaces immutable, so a box can never disagree with its original.

code

csharp · 26 lines
csharp
var counter = new Counter();
IIncrement viaInterface = counter;     // boxing: the interface variable holds a boxed copy
viaInterface.Increment();
viaInterface.Increment();
Console.WriteLine($"counter.Hits = {counter.Hits}");                    // 0
Console.WriteLine($"box Hits     = {((Counter)viaInterface).Hits}");    // 2

object boxed = counter;
((Counter)boxed).Increment();          // unboxes to a temporary copy; the box is not changed
Console.WriteLine($"boxed Hits   = {((Counter)boxed).Hits}");           // 0

Bump(ref counter);                     // generic call on the variable itself, no box
Console.WriteLine($"counter.Hits = {counter.Hits}");                    // 1

static void Bump<T>(ref T item) where T : IIncrement => item.Increment();

interface IIncrement
{
    void Increment();
}

struct Counter : IIncrement
{
    public int Hits;
    public void Increment() => Hits++;
}

go deeper

for a junior

Recall that interfaces are reference types: assigning a struct to an interface variable boxes a copy, exactly as assigning it to object does.

for a middle

Trace each copy in the snippet: the box made by the interface conversion, the temporary made by casting back, and why only the generic ref call reaches the original variable.

for a senior

Spot the pattern in review: mutable structs stored as interfaces in fields, parameters or collections, where state silently forks. Recommend immutability or a constrained generic path.

for a principal

Treat a mutable struct that implements an interface as a review flag, and steer the team toward immutable structs so an interface conversion costs an allocation, never a lost update.

## Interfaces are reference types An interface such as `IIncrement` is a **reference type**: a variable of that type holds a reference to an object on the managed heap. A struct is a **value type**: its variable holds the data itself. So when a `Counter` struct is assigned to an `IIncrement` variable, C# applies a **boxing conversion**, the same one it applies for `object`. The runtime allocates a box, copies the struct's current fields into it, and the interface variable refers to that box. From that moment there are two `Counter` values: the local and the boxed copy. ## Following the copies The snippet for this question makes three kinds of copy. Step by step: 1. `var counter = new Counter();` creates the original, with `Hits` at 0. 2. `IIncrement viaInterface = counter;` boxes a copy. `counter` and the box are now independent. 3. Two calls to `viaInterface.Increment()` run on the boxed copy, so the **box's** `Hits` becomes 2. `counter.Hits` is still 0. 4. `object boxed = counter;` makes a second, separate box, also with `Hits` at 0. 5. `((Counter)boxed).Increment()` unboxes. The result of an unboxing cast is a value, not a variable, so the compiler copies it into a hidden temporary and calls `Increment` on the temporary. The temporary is thrown away and the box still reads 0. 6. `Bump(ref counter)` passes the original variable by reference to a generic method, and the call inside it mutates `counter` itself: `Hits` becomes 1. Writing to the field directly, `((Counter)boxed).Hits++`, is rejected at compile time with `CS0445: Cannot modify the result of an unboxing conversion`. The method call compiles because calling a method on a temporary is legal, which is exactly why the lost update is silent. ## Which copy does each expression change? | Expression | What gets mutated | Visible through `counter`? | |---|---|---| | `counter.Increment()` | the local itself | yes | | `viaInterface.Increment()` | the boxed copy behind the interface | no | | `((Counter)boxed).Increment()` | a temporary unboxed copy | no, and not in the box either | | `Bump(ref counter)` with `where T : IIncrement` | the local, through the reference | yes | ## Mutating in place through an interface contract A generic method whose type parameter is constrained to the interface can call the interface's members on a `T` without converting `T` to the interface. For a call on a `T` value, the compiler emits a **constrained call**: when `T` is a struct that implements the member, the runtime calls the struct's own method on the storage location it was given. Combined with a `ref T` parameter, that storage location is the caller's variable, so the mutation sticks and nothing is boxed. How the `where` clause itself works is covered with generic constraints; what matters here is that the call never goes through a box. ## Where the pattern hides - **Interface-typed collections.** A `List<IIncrement>` holding `Counter` values stores boxes. `list[0].Increment()` mutates the box in the list, so the change persists there, but any `Counter` local the value came from never sees it. - **Interface-typed fields and parameters.** Passing a struct to a method that takes `IIncrement` hands over a fresh box each time; mutations inside the method are lost to the caller. - **Casting back to read.** `((Counter)viaInterface).Hits` reads a copy of the box's current state; it is fine for reading and useless for writing. ## Preventing it The robust fix is design, not care at every call site: - Make structs that implement interfaces **immutable** (a `readonly struct` with members that return new values), so a box and its original can never disagree. The trade-offs of struct design are covered with value-type trade-offs. - Where a mutable struct must be manipulated through a contract, use a **generic method constrained to the interface** and pass by `ref`. - When state really has to be shared, make the type a **class**: sharing one object is what reference types are for. The boxing still costs an allocation in the immutable case; it simply stops being a correctness problem. Nothing in the compiler flags the mutable case: the snippet for this question builds on .NET 10 without a single warning, even though two of its four mutations are lost. The only defence is knowing which expressions box and which ones copy, or removing mutation from the struct so the question never arises.

  • Why does ((Counter)boxed).Hits++ fail to compile while ((Counter)boxed).Increment() compiles?
    The result of an unboxing conversion is a value, not a variable, so assigning to one of its fields is rejected with CS0445: Cannot modify the result of an unboxing conversion. Calling a method is allowed because the compiler copies the value into a hidden temporary and calls the method on it. The temporary is discarded, so that mutation is lost without any warning.
  • If Counter were an immutable readonly struct, would the interface assignment still box?
    Yes. Converting a struct to an interface type allocates a box holding a copy. What disappears is the bug: with no mutating members, the box and the original can never disagree, so the copy is only a cost. Removing the allocation as well needs a generic path, a type parameter constrained to the interface, rather than an interface-typed variable.
  • What does list[0].Increment() do on a List<IIncrement> that holds a Counter?
    Adding the `Counter` to the list boxed a copy, and the list stores the reference. `list[0]` returns that reference, so `Increment` mutates the box inside the list and the change persists there: `((Counter)list[0]).Hits` reads 1. The `Counter` variable the value was first copied from is not affected.

  • Calling a method through an interface variable acts on the original struct.
  • An interface variable stores a struct inline, so no allocation happens.
  • Casting the interface variable back to the struct gives access to the original variable.
  • Calls through the interface change nothing at all, not even the box.
  • A generic method constrained to the interface boxes the struct just like an interface parameter.