SCA1005: MemberwiseClone of a Non-copyable Value
Do not call MemberwiseClone on what holds a non-copyable value.
Example
class Holder
{
private LockGuard _guard;
public Holder Clone() => (Holder)MemberwiseClone(); // SCA1005: the clone has a second guard
}
internal class Base
{
public Base Clone() => (Base)MemberwiseClone(); // SCA1005: an object of Derived is cloned as well
}
internal class Derived : Base
{
private LockGuard _guard;
}
How to Fix
Write the copy out: copy the fields that may be copied, and move or re-create what must not be. MemberwiseClone() makes a shallow copy, field by field.
A field of a class whose base class clones itself, such as Encoding, gets SCA1009 instead, since the call is in code that the analyzer cannot read. Writing the copy out does not answer that warning.
Details
What Gets the Warning
MemberwiseClone() is called in a class that has an instance field of a non-copyable type, its own or inherited, or in a non-copyable struct. A field that holds a container, such as a List<LockGuard>, does not count: the clone shares the list. The same warning is given for:
- the clone of MarshalByRefObject,
MemberwiseClone(bool), which Stream and Component inherit; - a method group of either, as in
Func<object> clone = MemberwiseClone;, which clones when the delegate is invoked; - a call on an object of a type parameter,
t.MemberwiseClone()withT : Holder. The analyzer judges it by the class that the type parameter is constrained to, since the object is of that class or of one derived from it.
Derived Classes
Where the class has no such field, the object that is cloned can be of a derived class that has one. If a derived class in the same compilation has such a field, the call gets this warning as a definite copy, and the message names that class and its field.
That includes a field of a constructed base class, such as the T field of Box<T> in class Derived : Box<LockGuard>. Where the field holds a captured parameter of a primary constructor, the message names the parameter.
A class that another assembly can derive from gets a warning as a possible copy, with an ID of its own (SCA1008). A sealed class and a struct have no derived class, and get no warning.
See Also
These articles explain the rule behind this warning:
- Fields, Interfaces and Async Members - the declarations that copy a value by themselves.
- SCA1008 - a class that another assembly can derive from.
- SCA1009 - a field or a binding behind a base class that clones itself.
Didn't add this analyzer yourself? See Why Am I Seeing This?