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

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

There is a newer version: 10.4.0.108396
Show newest version

Why is this an issue?

When you do not use the return value of a method with no side effects, it indicates that something is wrong. Either this method is unnecessary, or the source code does not behave as expected and could lead to code defects. For example, there are methods, such as DateTime.AddYears, that don’t change the value of the input object, but instead, they return a new object whose value is the result of this operation, and as a result that you will have unexpected effects if you do not use the return value.

This rule raises an issue when the results of the following methods are ignored:

Special cases:

  • Although string.Intern has a side effect, ignoring its return value is still suspicious as it is the only reference ensured to point to the intern pool.
  • LINQ methods can have side effects if they are misused. For example:
data.All(x =>
{
    x.Property = "foo";
    return true;
});

Such code should be rewritten as a loop because Enumerable.All<TSource> method should be used to determine if all elements satisfy a condition and not to change their state.

Exceptions

This rule doesn’t report issues on invocations with out or ref arguments.

How to fix it

Code examples

Noncompliant code example

data.Where(x => x > 5).Select(x => x * x); // Noncompliant
"this string".Equals("other string"); // Noncompliant

data.All(x =>  // Noncompliant
{
    x.Property = "foo";
    return true;
});

Compliant solution

var res = data.Where(x => x > 5).Select(x => x * x);
var isEqual = "this string".Equals("other string");

foreach (var x in data)
{
    x.Property = "foo";
}

Resources

Documentation

Articles & blog posts





© 2015 - 2025 Weber Informatics LLC | Privacy Policy