Code Analysis Code Analysis
Code Analysis Code Analysis
DocFX + Singulink = ♥

Search Results for

    SCA1001: Copy by Assignment

    Do not copy a non-copyable value by assignment.

    Example

    LockGuard copy = _guard;                       // SCA1001: a copy of the field
    
    ref LockGuard alias = ref _guard;              // OK: a reference
    LockGuard taken = NonCopyable.Move(ref _guard); // OK: moved, and the field is left empty
    

    How to Fix

    • Refer to the value with a ref local instead of copying it.
    • Move it out with NonCopyable.Move, which leaves the default value behind. See Moving Values.
    • Make the assignment the last use of a local, by reading what you still need first. See Fixing Common Warnings.
    • For a foreach, loop with a ref variable over a span of the elements, as the message says.

    Details

    A variable, a field or an array element is assigned a stored value, which copies it. That includes:

    • a variable that a pattern, a deconstruction or a foreach declares;
    • a value that is taken out of a box;
    • the copy of a stored value that a deconstruction or a foreach makes before it calls a Deconstruct that is not readonly.

    A local or a by-value parameter gets no warning at its last use. If a read would be the last use except that a catch, a finally or an exception filter still uses the variable, the message says so. A read inside an exception filter is never a last use.

    Two more cases get a warning whatever the value is, even a new one:

    • a second variable that a pattern declares for a value which it has given to another variable: see One Value Goes to One Variable;
    • the variable of a switch clause after a clause with a when that could have taken the same value: see Clauses of a Switch.

    See Also

    These articles explain the rule behind this warning:

    • New and Stored Values in Detail - what may be copied and what may not.
    • Last Use of a Variable - where a variable is a new value.
    • Patterns, Deconstruction and Tuples - what a pattern copies.
    • Boxes and Unions - taking a value out of a box.

    Didn't add this analyzer yourself? See Why Am I Seeing This?

    © Singulink. All rights reserved.