All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S1121.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

A common code smell that can hinder the clarity of source code is making assignments within sub-expressions. This practice involves assigning a value to a variable inside a larger expression, such as within a loop or a conditional statement.

This practice essentially gives a side-effect to a larger expression, thus making it less readable. This often leads to confusion and potential errors.

Exceptions

Assignments inside lambda and delegate expressions are allowed.

var result = Foo(() =>
{
   int x = 100; // dead store, but ignored
   x = 200;
   return x;
}

The rule also ignores the following patterns:

  • Chained assignments
var a = b = c = 10;
  • Assignments that are part of a condition of an if statement or a loop
while ((val = GetNewValue()) > 0)
{
...
}
  • Assignment in the right-hand side of a coalescing operator
private MyClass instance;
public MyClass Instance => instance ?? (instance = new MyClass());

How to fix it

Making assignments within sub-expressions can hinder the clarity of source code.

This practice essentially gives a side-effect to a larger expression, thus making it less readable. This often leads to confusion and potential errors.

Extracting assignments into separate statements is encouraged to keep the code clear and straightforward.

Code examples

Noncompliant code example

if (string.IsNullOrEmpty(result = str.Substring(index, length))) // Noncompliant
{
  // do something with "result"
}

Compliant solution

var result = str.Substring(index, length);
if (string.IsNullOrEmpty(result))
{
  // do something with "result"
}

Resources





© 2015 - 2024 Weber Informatics LLC | Privacy Policy