All rules
CA2246Usage Enabled by default: As suggestion

Do not assign a symbol and its member in the same statement

Do not assign a symbol and its member in the same statement

Microsoft docs

Description

Assigning a symbol and its member, that is, a field or a property, in the same statement is not recommended. It is not clear if the member access was intended to use the symbol's old value prior to the assignment or the new value from the assignment in this statement. For clarity, the multi-assign statement must be split into two or more simple assignment statements.

Cause

A symbol and its member were assigned in the same statement. For example:

How to fix violations

To fix violations, split the multi-assign statement into two or more simple assignment statements. For example, the following code snippet shows a violation of the rule and a couple of ways to fix it based on the user intent:

Example

public class C
{
    public C Field;
}

public class Test
{
    public void M(C a, C b)
    {
        // Let us assume 'a' points to 'Instance1' and 'b' points to 'Instance2' at the start of the method.
        // It is not clear if the user intent in the below statement is to assign to 'Instance1.Field' or 'Instance2.Field'.
        // CA2246: Symbol 'a' and its member 'Field' are both assigned in the same statement. You are at risk of assigning the member of an unintended object.
        a.Field = a = b;
    }
}

When to suppress

Do not suppress violations from this rule.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0