Why is this an issue?
Dead stores refer to assignments made to local variables that are subsequently never used or immediately overwritten. Such assignments are unnecessary and don’t contribute to the functionality or clarity of the code. They may even negatively impact performance. Removing them enhances code cleanliness and readability. Even if the unnecessary operations do not do any harm in terms of the program’s correctness, they are - at best - a waste of computing resources.
Exceptions
No issue is reported when
- the analyzed method body contains
tryblocks - a lambda expression captures the local variable
- the variable is unused (case covered by Rule {rule:csharpsquid:S1481})
- it’s an initialization to
-1,0,1,null,true,false,""orstring.Empty
How to fix it
Remove the unnecessary assignment, then test the code to make sure that the right-hand side of a given assignment had no side effects (e.g. a method that writes certain data to a file and returns the number of written bytes).
You can also use discards (rather than a variable) to express that result of a method call is ignored on purpose.
Code examples
Noncompliant code example
int Foo(int y)
{
int x = 100; // Noncompliant: dead store
x = 150; // Noncompliant: dead store
x = 200;
return x + y;
}
Compliant solution
int Foo(int y)
{
int x = 200; // Compliant: no unnecessary assignment
return x + y;
}
Resources
Standards
Related rules
- {rule:csharpsquid:S2583} - Conditionally executed code should be reachable
- {rule:csharpsquid:S2589} - Boolean expressions should not be gratuitous
- {rule:csharpsquid:S3626} - Jump statements should not be redundant