Analysis of integer values (integral arithmetic)
ReSharper for Visual Studio Code can track the flow of integer values through your code and report redundant or possibly erroneous statements. It supports all C# integral numeric types — int, uint, byte, sbyte, short, ushort, long, and ulong — and warns you about the following issues:
relational/equality operators that always evaluate to
trueorfalse,unreachable
switchcases checkingintvalues,meaningless arithmetic operations, such as multiplication by
1or addition of0(except literals or constants: ReSharper for Visual Studio Code assumes that expressions likex + 0are intentional),possible
intoverflows,possible division by
0,possible errors in invocations of
System.Mathmethods,the above issues in enumeration types with the corresponding underlying types.
How it works
ReSharper for Visual Studio Code narrows down the possible range of values for each integer according to possible outcomes of all statements and expressions that can produce or affect that integer. Let's consider some examples.
ReSharper for Visual Studio Code can deduce that temp < 0 in the example below will always evaluate to false because Math.Abs always returns a non-negative value.
In the following example, ReSharper for Visual Studio Code infers that by the last return, the value of input is in the range of -100 ... 100, and when divided by a larger divider, it will be truncated towards zero.
Refine analysis with annotations
There are two JetBrains.Annotations attributes ([NonNegativeValue] and [ValueRange(from, to)]) for analysis of integer values.
You can use these attributes with type members returning int and with int parameters to specify known constraints and thus improve analysis precision.
Here is an example of annotating the method parameter with [NonNegativeValueAttribute] to refine the analysis within the method body. Knowing that the parameter is non-negative, ReSharper for Visual Studio Code can report all redundant operations on that parameter:
The following example demonstrates how annotating a method can help find redundant checks around its usages: