Code inspection: Possibly impure struct method is called on readonly variable: struct value always copied before invocation

Last modified: 11 February 2024

Consider the following code:

We end up getting 0 in the output, while it might seem that calling IncrementValue() beforehand should make it 1. This happens because when we access a readonly field of a value type, a copy of it is created to prevent the caller from mutating the field.

_readonlyStruct.IncrementValue() in the above example creates a copy of _readonlyStruct, changes its Value field to 1, and then the copy is discarded.

However, we only have this kind of problem with impure methods — methods that change the object state, like IncrementValue() above does. Calling a pure method in a similar situation is not a problem because whether it is called on a copy or not, it doesn't change its state, and we'll get the expected result from the method anyway.