ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code Inspection: Impure method is called for readonly field of value type

Last modified: 30 September 2021

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.