SCA1009: Non-copyable Value Behind a Base Class That Clones Itself
Do not hold or bind a non-copyable value in a class whose base class clones itself.
Example
sealed class PinnedEncoding : UTF8Encoding
{
private GCHandle _pinned; // SCA1009: Encoding's Clone copies the handle
private readonly HandleHolder _holder = new(); // OK: the clone shares the object that holds a handle
}
sealed class HandleHolder
{
public GCHandle Handle; // OK: no class that clones itself is a base of HandleHolder
}
The same goes for a non-copyable value that a generic class holds, where the class derives from one that clones itself. The comments show where each warning goes, in the library and in a project that uses it:
// In a library
public class TaggedCulture<[NonCopyable] T> : CultureInfo
{
public T Tag; // SCA1009: in the library's own build
public TaggedCulture(string name) : base(name) { }
}
public static class Cultures
{
public static TaggedCulture<T> Make<[NonCopyable] T>() => new("en-US"); // SCA1009: in the library's own build
}
// In a project that uses it
sealed class GuardCulture : TaggedCulture<LockGuard> // SCA1009: CultureInfo's Clone copies the guard in Tag
{
public GuardCulture() : base("en-US") { }
}
sealed class HolderCulture : TaggedCulture<GuardHolder> // OK: the clone shares the holder
{
public HolderCulture() : base("en-US") { }
}
static object Uses(GuardCulture own)
{
var culture = Cultures.Make<LockGuard>(); // no warning: the type still shows the guard
var copy = culture.Clone(); // SCA1009: the clone copies the guard in Tag
CultureInfo plain = culture; // SCA1009: hands the object to code that can clone it
CultureInfo mine = own; // OK: GuardCulture has its warning where it binds LockGuard
return CultureInfo.ReadOnly(culture); // SCA1009: ReadOnly clones what it is given
}
How to Fix
- A warning that says no symbol list line says whether the base class's code clones an object means that the base class is of a library that was not built with the analyzers. Add the symbol list line that fits what the class does: see A Base Class That Is Not Known.
- A warning on a use, such as
culture.Clone(), a conversion or a call ofVisit(Action<Document>), means that the use lets other code clone the object. The object's class binds a non-copyable type behind a base class that clones itself. To fix it:- bind a class that holds the value by reference, such as
TaggedCulture<GuardHolder>, so that a clone shares the value: see Bindings; - if the member neither clones the object nor hands it on, add a line for the member that says so. Or, once the class's
cloneslines name every member that does either, write the class's line asclones=complete. See Symbol List Lines; - otherwise avoid the use, or suppress the warning where the object is never cloned. Uses lists the uses that get the warning.
- bind a class that holds the value by reference, such as
- Hold the value in an object of a class that your class refers to. The clone copies the reference, and both objects share the one value.
- Bind a class that refers to the value, such as
TaggedCulture<GuardHolder>, instead of the value. Its objects get no warning wherever they are used. - For a class of another library, name its members that clone in a symbol list file: see Symbol List Lines.
- Suppress the warning where no object of the class is ever cloned.
Writing a copy of your own does not answer the warning on a field. The base class's clone copies the field whatever your own code does, and a call of MemberwiseClone in your class gets SCA1005 besides:
public sealed class GuardedCulture : CultureInfo
{
private LockGuard _guard; // SCA1009: CultureInfo's Clone copies the guard, whatever Copy does
public GuardedCulture() : base("en-US") { }
public GuardedCulture Copy()
{
var copy = (GuardedCulture)MemberwiseClone(); // SCA1005: the clone has a second guard
copy._guard = default;
return copy;
}
}
Details
A Class That Clones Itself
Some classes clone their objects field by field with MemberwiseClone() in code of their own, such as the Clone method of Encoding. The clone copies every field of a class that derives from them as well. The analyzer cannot see the call in another assembly, so a clones line of the symbol list names such a class. The built-in framework symbol list has one for every class of the framework that clones itself, such as Encoding, CultureInfo and Calendar. For a class of another library, add its line to a symbol list file:
# NonCopyableSymbols.txt: Contoso's Document clones itself in its Copy method
T:Contoso.Document;clones
M:Contoso.Document.Copy;clones
A Base Class That Is Not Known
A class of a library that was not built with the analyzers may clone itself too, and the analyzer cannot tell. So a class of the project that derives from one gets the warning on each field that holds a non-copyable value, until a symbol list line says what the base class does:
sealed class PinnedDocument : Contoso.Document // Contoso was not built with the analyzers, and no line names Document
{
private GCHandle _pinned; // SCA1009: nothing says whether Document clones itself
}
| What you know | Line | What it does |
|---|---|---|
| The base class clones itself | T:Contoso.Document;clones |
The field keeps its warning, since a clone copies it |
| Neither the base class nor a class above it clones its objects | T:Contoso.Document;clones=none |
The field gets no warning |
| No code of the assembly copies a non-copyable value | A:Contoso;trusted |
No field behind a class of the assembly gets the warning |
The analyzer cannot check a clones=none or a trusted line, so write one only for code that you know. See Clones and Trusted.
Two kinds of base class need no line. The framework's classes are covered by the built-in framework symbol list, which names every one of them that clones itself. A class of a library that was built with the analyzers is checked in that library's own build. A Microsoft library outside the .NET, ASP.NET Core and Windows Desktop shared frameworks, such as WinUI, counts as another library. So does an assembly that only the .NET Framework or one platform has, such as System.Messaging or Mono.Android.
Fields
A class of the project that derives from a class that clones itself, at any depth, gets the warning on each field that holds a non-copyable value:
| Field | Warning? |
|---|---|
| A field of a non-copyable type, a GCHandle included | Yes |
| A tuple or a struct that holds a non-copyable value | Yes |
A field of a type parameter that is marked [NonCopyable] |
Yes, with a text that says so: see below |
| A container, or an object of a class that holds the value | No: the clone shares it |
| A static field | No |
A field that a call of MemberwiseClone in the project copies as well |
Yes, and the call gets SCA1005 |
The field of a marked type parameter gets the warning in the build of its own project, since a clone copies what is bound to it. Suppress it there only where the class's own code never clones its objects. A project that binds a non-copyable type to it gets the warning where it calls, on such an object, a member that clones, or where it hands the object to other code. A field of a type parameter that is not marked gets no warning, but each binding of a non-copyable type to it gets its own (see Bindings).
Bindings
A non-copyable type that is bound to a type parameter of such a class gets the warning where the project writes the binding:
- as the base class of a class;
- in an object creation, one with a
dynamicargument included.
A generic class of another library is judged by its type arguments, whether its type parameter is marked or not. Where the type parameter is not marked, a use of such a class of another library gets SCA1020 as well.
Uses
The binding can also be in the type of a value, as in the TaggedCulture<LockGuard> that a call returns or a new T() makes, or in the base list of a class of another assembly. Such an object gets the warning where something can clone it:
A member that clones is called on it, or is given it, such as
culture.Clone()orCultureInfo.ReadOnly(culture). Aclonesline says that a member clones its object, or the object that it is given, or hands it to code that can, asPrinterSettings.DefaultPageSettingsdoes: the page settings that it returns refer back to the printer settings.A member's signature shows that it can hand it on as the class that clones itself, a class above it,
objector an interface. A symbol list line for the member with no marker says that it never hands the object itself to other code.- What comes out of the member, its result, an
outorrefparameter, or a property or field that can be read, counts where such a type is anywhere in its type, as inDocument WithTitle(string),Task<Document>orList<Document>.Enumerator. - What goes in, a parameter, a property or field that can be set, or the handler of an event where it is subscribed to, counts where something in its type can take such a type in. That is a delegate that takes one, as in
Visit(Action<Document>)or theobject senderof anEventHandler, or another type that can take one in, as inSortWith(IComparer<Document>)orFill(List<Document>). A delegate reverses the direction for its own parameters, soAction<Action<Document>>, which only gives the caller a place to send documents, does not count.
- What comes out of the member, its result, an
A member that no line names is called on it, and no
clones=completeline makes known the members of the class that declares it. Without such a line, any member of that class may be one that clones. Which line makes them known depends on where the declaring class stands:The class that declares the member Its assembly The class whose line must say clones=completeThe class that clones itself, or a class above it, such as objectAny The class that clones itself A class that writes the binding in its own base list, as Bound : Tagged<GCHandle>doesThe assembly of the class that clones itself, not built with the analyzers The class that clones itself, or that class A class that writes the binding in its own base list Another assembly, not built with the analyzers That class Any other class between the class that clones itself and the object's own class The assembly of the class that clones itself, or one built with the analyzers The class that clones itself, or the class between Any other class between Another assembly, not built with the analyzers The class between The line can be in any symbol list file, and a plain
clonesline for any of these classes changes nothing. Two kinds of class are not in the table:- A class of the project, or of an assembly that was built with the analyzers, that writes the binding in its own base list. The analyzer judges it in its own build instead.
- A generic class of an assembly that was not built with the analyzers whose binding comes from its own type argument alone, as
Far<Guard>whereFar<T> : Doc. Its members get SCA1020 instead. Where a base list above such a class also binds a non-copyable type, asBoth<T> : Tagged<GCHandle>does, the class is in the table for that binding.
The framework's own classes that derive from a class that clones itself, such as UTF8Encoding or GregorianCalendar, have lines of their own in the built-in framework symbol list that say
clones=complete.It is handed to other code as a type that hides its binding: converted to the class that clones itself, a class above it,
object,dynamicor an interface, written or not. The conversion can be in a variable, an argument or a return; in a??, a deconstruction or a spread; through variance; in aforeachvariable, a pattern or a hole of an interpolated string; in the return of an override; or in the receiver of an extension that a pattern calls, such as aDeconstructor aGetAwaiter. A binding of its type to a type parameter that is not marked, or to a marked one whose constraint is such a type, counts as well.
A line for a member says what that member does, not what an override of it does. A member declared in the class that binds the type, or in a class between it and the class that clones itself, is judged by its own line and its own signature. So an override of GetFormat that returns the culture itself gets the warning. A member of a base class can run an override too: see Overrides That a Base Class Runs.
Any other member that it inherits gets no warning, as with a member of a container's own type. Where a class's line says clones=complete, the analyzer counts a member that no line names as one that neither clones the object nor hands it on. The lines must say what a signature cannot show, such as a member that stores the object in another object that it returns, or that gives it to a visitor interface, a registry or a wrapper class. A method group is a use of its member, and the Target of its delegate is not checked, as reflection is not:
var culture = Cultures.Make<LockGuard>();
_ = culture.Name; // OK: the line of CultureInfo says clones=complete, and no line names Name
_ = culture.Parent; // OK: the built-in list says that Parent never hands back the culture itself
var copy = culture.Clone(); // SCA1009: Clone clones it
Func<string> name = culture.ToString; // OK: ToString neither clones it nor hands it on
Func<object> clone = culture.Clone; // SCA1009: a method group of Clone is a use of it
The argument of a member on the symbol list gets the warning unless the line marks the member borrows, which says that it uses what it is given during the call and keeps nothing of it. List<CultureInfo>.Add keeps the culture, and so does Task.FromResult; Monitor.Enter, which lock calls, keeps nothing.
A container of such objects that is converted to a type that hides them gets the warning too. A class of the project that binds the type in its own base list, or whose base class does, gets the warning there, and its objects get none for the clone where they are used. Where that base list binds the type to a type parameter that is not marked, of a generic of the project, the conversion of its objects to the base class gets SCA1023 as well, for the code of that generic.
Converting the object to dynamic gets the warning, and so does converting a container whose type shows the binding. What the dynamic binder does at run time with a member of a dynamic object is not checked. That includes the field of an object whose own type shows no binding:
sealed class TaggedHolder
{
public TaggedCulture<LockGuard>? Culture; // OK: the field's type shows the binding
}
dynamic direct = culture; // SCA1009: hands the culture to code that can clone it
dynamic holder = new TaggedHolder { Culture = culture }; // no warning: what the binder does with the field is not checked
Overrides That a Base Class Runs
The code of a base class can call a virtual member of its own object, and the call runs the override of a class below it. CultureInfo.GetFormat reads NumberFormat, so it runs an override of NumberFormat. The analyzer cannot tell which member of a base class calls which virtual member, so it counts every member of that base class as one that can run the override. For an event of the base class, adding a handler and removing one both count.
// A library that was not built with the analyzers: Bound overrides NumberFormat with a getter that clones the culture,
// and a 'clones' line names the override
Bound culture = Cultures.MakeBound();
_ = culture.NumberFormat; // SCA1009: the line says that the override clones
_ = culture.GetFormat(typeof(NumberFormatInfo)); // SCA1009: GetFormat can run the override
_ = culture.Name; // SCA1009: so can any other member of CultureInfo
_ = culture.GetType(); // OK: the code of object calls no virtual member
What a member of the base class gets depends on the override:
| The override | A member of the base class |
|---|---|
A clones line names it |
Gets the warning |
| It is of a library that was not built with the analyzers, and no line says what it does | Gets the warning until a line says that the override does not clone: a line for the override with no marker, or a clones=complete line that covers its class |
It is of the project or of a library that was built with the analyzers, and no clones line names it |
No warning |
The analyzer counts what the base class can run:
- An override of a member that the base class has, as a member of its own or of a class above it.
- A member that implements a member of an interface in a class below. The base class can use its own object as an interface, even one that it does not implement itself.
- What those members can run in turn. An override in a class between can call a virtual member of its own class, which a class further down overrides.
Three kinds of member do not count:
- A member of the class that clones itself, or of a class above it. The
cloneslines of that class say what the members of those classes do. There is one exception: an override there that aclonesline names, such as aCloneCorethat the class overrides with a clone. A member of a class above it that can run it gets the warning until a line for that member says whether it does. - An override of a member that clones already, such as an override of
Clone. Thecloneslines name the members that run it. - An override in a class of the framework. The lines of the built-in framework symbol list cover those, and a
clonesline of your own for one changes nothing for the members of its base class. A framework class between still passes a call on, so an override of one of its virtual members in a class below it counts.
A constructor of a base class can run an override too. That needs no warning of its own: the place that creates the object binds the type, and gets the warning there (see Bindings).
Symbol List Lines for a Class That Clones Itself
| You write | You vouch for |
|---|---|
T:Contoso.Document;clones |
The class clones its objects field by field in code of its own. The analyzer counts every member that no line names as one that can clone |
M:Contoso.Document.Copy;clones |
The member clones its object, or the object that it is given, or hands it to code that can, directly or through other members. A property's line starts with P:. An event's line starts with E: and covers both adding and removing a handler |
M:Contoso.Document.WithTitle(System.String) |
The member never hands the object that it is called on to other code. The line vouches for everything that the member does, what it calls included. It does not vouch for an override of it, or for an override that it runs in a class below the class that clones itself |
T:Contoso.Document;clones=complete |
The clones lines name every member of the class that clones the object or hands it on, so a member with no line does neither |
M:Contoso.Registry.Note(System.Object);borrows |
The member uses the object that it is given during the call and keeps nothing of it |
Warning
clones=complete vouches that the clones lines name every member that clones the object or hands it to other code, even one that only gives it to a visitor interface, a registry or a wrapper. The analyzer cannot check that. Without complete, the analyzer judges each member by its own line: the safe choice when you cannot vouch for all of them.
A member line names a member that a project which uses the library can call. A member that clones the object or hands it on through a private or internal member of its class needs the line, not the helper: a project that references the library cannot see the helper, and a line for it has no effect there. A class can also sit between the class that clones itself and the object's own class. Where it is of a library that was not built with the analyzers, write a type line for it, such as T:Contoso.TaggedDocument`1;clones=complete.
A library that is built with the analyzers gets SCA1008 for each member of its own such class that another project can call and that clones its object without a line, with MemberwiseClone or through a member that clones. The warnings help it complete its shipped file before it writes clones=complete on the type line, but they do not find a member that clones through a private helper or hands the object on. For a library that is not built with the analyzers, the lines are your statement. The lines of the built-in framework symbol list are backed by a scan of the framework's code.
Which Warning a Use Gets
Each reason has one ID:
| What the code does | Warning |
|---|---|
Calls MemberwiseClone on an object or a struct that holds a non-copyable value |
SCA1005 |
| Holds or binds a non-copyable value behind a base class that clones itself, or uses such an object as Uses describes, a binding to a type parameter that is not marked included | SCA1009 |
Declares a member that clones its own object and has no clones line, in a library's class that clones itself and that another project can derive from or bind a type to |
SCA1008 |
| Uses a member of a generic whose type parameter is not marked, with a non-copyable type bound, for what the member does with the value | SCA1020 |
| Uses a container as a type that hides it where no binding to a class that clones itself is involved, or converts an object of a class of the project to its base class where its binding is to a type parameter that is not marked | SCA1023 |
A use gets two warnings only where it has two reasons, such as new TaggedPlain<LockGuard>() of a library whose type parameter is not marked: SCA1009 for the binding, and SCA1020 for the constructor's own code. A #pragma or a suppression attribute for SCA1005 does not cover this warning.
See Also
These articles explain the rule behind this warning:
- Fields, Interfaces and Async Members - the declarations that copy a value by themselves.
- Symbol List Format - the
clonesline. - Classes That Clone Themselves - the framework's classes.
Didn't add this analyzer yourself? See Why Am I Seeing This?