Self Assignment

ID

csharp.self_assignment

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

CWE:480, reliability, suspicious-comparison

Description

Reports simple assignments whose left-hand side and right-hand side are the same expression, for example x = x. The assignment is a no-op and almost always signals a copy-paste mistake or a missing this. qualifier on one side.

Rationale

A statement like count = count; does nothing, yet it reads as if it should. The most common real-world cause is a constructor or setter that means to copy a parameter into a field but forgets to qualify the field, e.g. writing name = name; instead of this.name = name; — leaving the field unassigned. Flagging the no-op surfaces the bug.

public class Account
{
    private int balance;

    public Account(int balance)
    {
        balance = balance;          // FLAW — assigns the parameter to itself; field stays 0
    }

    public void Reset(int balance)
    {
        this.balance = balance;     // OK — qualified, copies parameter into the field
        this.balance += balance;    // OK — compound assignment is not a no-op
    }
}

Remediation

Decide which side was intended. If a field should receive a parameter, qualify the field with this. (this.balance = balance;). If the statement is genuinely redundant, delete it.