Variable assigned to itself
ID |
vbnet.correctness.self_assignment |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Redundant Operation |
Language |
VB.NET |
Description
Flags an assignment whose target and source are the same expression: a local assigned to
itself (subtotal = subtotal), a field assigned to itself (Me.Total = Me.Total), or an
indexed element assigned to itself (values(0) = values(0)). Only assignment statements are
matched, so an equality test that happens to compare a value with itself is not reported
here, and neither is a compound update such as Total = Total + delta, which reads and
writes the same variable but is not a no-op.
Rationale
The statement compiles and runs, and changes nothing — dead code that every later reader has
to stop and reason about. More importantly, it is usually the visible symptom of a value that
never got stored. The classic VB.NET case is a member and a parameter sharing a name: inside
the method the unqualified name resolves to the parameter, so Discount = Discount copies
the parameter over itself and the field keeps its previous value. The object then quietly
carries stale state and the defect surfaces far from the assignment, in a total that never
changes or a setting that never takes effect, which makes it expensive to track down.
The following code illustrates the pattern detected by this rule:
Public Sub Recalculate(ByVal lineCount As Integer)
Dim subtotal As Decimal = 0D
' FLAGGED: Variable assigned to itself
subtotal = subtotal
Total = subtotal
End Sub
Remediation
Remove the statement when it is simply dead, or fix the operand that was meant to differ. When a
parameter shadows a member of the same name, qualify the assignment target with Me..
' Before: the parameter is assigned to itself and the field is never updated
Public Sub SetDiscount(ByVal Discount As Decimal)
Discount = Discount
End Sub
' After
Public Sub SetDiscount(ByVal Discount As Decimal)
Me.Discount = Discount
End Sub