SCA1002: Copy by Return
Do not copy a non-copyable value by returning it.
Example
LockGuard Get() => _guard; // SCA1002
LockGuard Take() => NonCopyable.Move(ref _guard); // OK
ref LockGuard Get() => ref _guard; // OK: returns a reference
How to Fix
- Return by reference, where the caller should use the value in place.
- Move the value out of the field, where the caller should own it.
- Return a local, a by-value parameter or a new value, which ends with the method.
Details
A return by value copies a value that something else still holds. You get this warning for:
- a method or a property that returns the value of a field or a reference by value;
- a lambda, a local function or an iterator that returns a variable which lives on after it returns, such as a captured variable;
- a member that returns a parameter of its type's primary constructor, which the compiler keeps in a field;
- a method that returns a variable which a
finally, or the end of ausingscope, uses after thereturnhas read its value.
class Holder(LockGuard guard) { public LockGuard Take() => guard; } // SCA1002: 'guard' is a field
See Returned Variables and Variables That Live On.
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.
- Moving Values - the move helper.
Didn't add this analyzer yourself? See Why Am I Seeing This?