V3155. The expression is incorrect or it can be simplified.

The analyzer has detected a suspicious expression whose result will always be equal to one of the operands. Either such expressions are made redundant intentionally to convey a certain idea to future maintainers or they are simply errors.

The following example demonstrates a simple case of such an error:

var a = 11 - b + c * 1;

The 'c' variable is multiplied by '1', which is a redundant operation and may signal a typo if the programmer actually meant to multiply the variable by some other value, say, 10:

var a = 11 - b + c * 10;

The next example is taken from a real project. Here, redundancy was added on purpose but not quite properly:

detail.Discount = i * 1 / 4M;

What the programmer meant by this expression is that the 'i' variable is to be multiplied by one fourth. Yes, they could have written it as 0.25, but the value 1/4 better conveys the logic of the algorithm.

But this expression is not very well implemented. The 'i' variable is first multiplied by 1 and only then does the division take place. True, the result is still the same, but code like that may be misleading, which is the reason why the analyzer pointed it out.

To make the code clearer and stop the analyzer from issuing the warning, parentheses should be added:

detail.Discount = i * (1 / 4M);

Another real-life example:

public virtual ValueBuffer GetIncludeValueBuffer(int queryIndex)
{
  return queryIndex == 0 
    ? _activeQueries[_activeIncludeQueryOffset + queryIndex].Current
    : _activeIncludeQueries[queryIndex - 1].Current;
}

In this case, the '_activeIncludeQueryOffset' variable will always be added to zero because of the check 'queryIndex == 0' before it. It does not look like an error, but the code can be simplified:

public virtual ValueBuffer GetIncludeValueBuffer(int queryIndex)
{
    return queryIndex == 0 
    ? _activeQueries[_activeIncludeQueryOffset].Current
    : _activeIncludeQueries[queryIndex - 1].Current;
}

Note. The analyzer does not report a suspicious expression if it finds another similar expression next to it. For example:

A[i+0]=1;
A[i+1]=10;
A[i+2]=100;
A[i+3]=1000;
A[i+4]=10000;

The 'i + 0' expression is redundant, but it is followed by a series of similar expressions of the 'i + literal' pattern. This suggests that the first expression, where the variable is added to 0, was written on purpose for the sake of consistent style.

This diagnostic is classified as:


Bugs Found

Checked Projects
412
Collected Errors
14 132
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →
Accept