SCA1004: Boxing a Stored Value
Do not box a stored non-copyable value.
Example
object copy = guard; // SCA1004: boxes a copy of a stored value
IDisposable boxed = myLock.Enter(); // OK: the new guard moves into the box
boxed.Dispose(); // OK: runs on the box
How to Fix
- Box a new value, which moves into the box: the box then holds the only instance.
- Move the stored value out first, with NonCopyable.Move.
Details
A stored value of a non-copyable type is converted to object or an interface, which boxes a copy of it. That holds whether a conversion, as or a pattern does it: in guard is IDisposable d, d is a boxed copy. A bare type test boxes nothing that can be used.
A type pattern from a struct to a type parameter can box as well: guard is T t boxes a copy of a stored guard.
See Also
These articles explain the rule behind this warning:
- Boxes and Unions - boxing, and what takes a value out of a box.
- New and Stored Values in Detail - what may be copied and what may not.
Didn't add this analyzer yourself? See Why Am I Seeing This?