Change this condition so that it is not always evaluated as 'true'

Why is SonarQube complaining about this piece of code?

enter image description here

I checked this code, and this value is not always true.

public static void WriteJson(object value) { decimal decimalValue = ((decimal?)value).Value; int intValue = (int)decimalValue; if (decimalValue == intValue) Console.WriteLine(intValue); else Console.WriteLine(decimalValue); Console.ReadKey(); } 

Why is SonarQube complaining about this?

+5
source share
3 answers

The falsified result is due to the imperfection in our analytical analysis of the data stream - it does not take into account castings between floating point numbers and integers (for now) and cannot recognize when the floating point number was truncated.

I will try to refine it a bit: the data flow analysis mechanism monitors the values โ€‹โ€‹of local variables in the methods being analyzed, and when a new value is assigned to a variable, the engine creates a special object that represents the actual value.When you assign one variable to another variable, this object remains the same. For instance:

 var x = 5; // the symbol of x is associated with value_0 var y = x; // the symbol of y is associated with value_0 if (x == y) // value_0 is compared with value_0 --> always true 

The values โ€‹โ€‹we assign do not contain type information (yet), and we cannot detect (yet) changes in cases such as yours:

 var x = 5.5; // the symbol of x is associated with value_0 var y = (int)x; // the symbol of y is associated with value_0 (wrong) if (x == y) // false positive 

and we generate false positives, but they are relatively rare because most casts do not generate new values.

Thanks for the feedback, we will consider that in the near future .

+7
source

I am not an expert on SonarQube, but I think this is because SonarQube detects that you set intValue to the rounded decimalValue form. And again, you are comparing decimalValue with the decimal form intValue . Thus, in many cases, he will return the "truth."

To see how this happens, suppose decimalValue is "123.0". Then intValue will be exactly "123". Then we compare "123.0" (decimalValue value) with "123.0" (intValue value after decimal conversion) with the "if" operator, which will return true. This will play for all integers.

0
source

It seems like SonarQube detects that you are assigning the same value to both variables, assume that the value passed to the method is 2

  1. decimal decimalValue = 2 2. int intValue = (int)decimalValue; 

therefore decimalValue = 2 and intValue = 2

The C # compiler will obviously pass it int , so if you pass 2.5 , the if comparison will not always evaluate to true . But most likely, SonarQube just does not know about casting. Therefore, it is always considered true.

0
source

Source: https://habr.com/ru/post/1271418/


All Articles