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

Search Results for

    SCA1011: Auto-property of a Non-copyable Type

    Do not declare an auto-property of a non-copyable type.

    Example

    public LockGuard Guard { get; set; }           // SCA1011: the getter returns a copy
    public LockGuard Guard;                        // OK: a field
    public ref LockGuard Guard => ref _guard;      // OK: a property that returns a reference
    

    How to Fix

    Use a field, or a property that returns a reference.

    Details

    An auto-property has a non-copyable type, and its getter returns a copy of the backing field.

    Two things are auto-properties without being written as one, and get this warning with a text of their own:

    Members of Anonymous Types

    A member of an anonymous type gets a warning where the object is created, as in new { Name = name, Lock = myLock.Enter() }. Every read of such a member in the code is a copy of a field. The members that the compiler writes for the type copy it too, although the code shows no copy: its ToString, Equals and GetHashCode, and with, which makes a second object. Use a tuple, or a class with a field.

    Positional Parameters of Records

    A positional parameter of a record gets a warning, even where the record declares the member itself as a property that returns a reference. The Deconstruct method that the compiler writes for the record reads the member by value. Declare the Deconstruct method yourself, or give the type an ordinary constructor.

    See Also

    These articles explain the rule behind this warning:

    • Fields, Interfaces and Async Members - the declarations that copy a value by themselves.

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

    © Singulink. All rights reserved.