Search code examples
c#if-statementnumbersoperatorsrelational

Why does this number gets detected as bool?


I'm checking if value ir between 0 and -0.2 like so:

float value = -0.1;
if (0 < value > -0.2f) { }

But I get error operator '>' cannot be applied to operands of type 'bool' and 'float'. I know, I could to that in other way using && operator in that if sentence, but I want to know, why does it gets detected as bool?


Solution

  • Take a look at this:

    0 < value > -0.2f
    

    Firstly 0 < value is evaluated, it returns bool value then it tries it compare bool to float number -0.2f, so it returns error, because it is not permitted.

    You want to check if value is less and if value is greater than, so this is what you want to do:

    if (0 < value && value > -0.2f) { }