SCA1006: Member Run on a Copy Through a Read-only Reference
Do not use a member that is not readonly through a read-only reference to a non-copyable value.
Example
void Close(in LockGuard guard) => guard.Dispose(); // SCA1006: disposes a copy
void Close(ref LockGuard guard) => guard.Dispose(); // OK
How to Fix
- Make the member
readonly, if it changes nothing. - Reach the value through a reference that is not read-only, such as a
refparameter. - Move a stored value out before calling a member on it, where it was a conditional, a
switchexpression, a??or a cast.
Details
A member that is not readonly is used on a value of a non-copyable type through a read-only reference, so the compiler runs it on a copy, and what it changes is lost. For a value of a marked type parameter, that applies to every member, since the compiler cannot know which are readonly.
A member on a temporary copy that the compiler makes from a stored value gets the same warning:
- a conditional (
?:), aswitchexpression and a??by value; - a conversion that gives a value, such as the cast that unwraps a nullable.
See Also
These articles explain the rule behind this warning:
- Read-only References and Temporary Copies - where the compiler runs a member on a copy.
- Copies You Cannot See - the usual cases, and their fixes.
Didn't add this analyzer yourself? See Why Am I Seeing This?