Zero Coalescing Operation

I get strange results from this method:

public static double YFromDepth(double Depth, double? StartDepth, double? PrintScale)
{               
    return (Depth - StartDepth ?? Globals.StartDepth) * PrintScale ?? Constants.YPixelsPerUnit ;
}

When I pass null to StartDepth, coalescing fails because it evaluates to "Depth - StartDepth", representing the first conversion of StartDepth to the default value of 0 (lowered?) Instead of first looking to see if it is null and replaces instead. Globals.StartDepth.

Is this a famous thing? I was able to do this work by adding brackets, but I really did not expect everything to work like that.

+3
source share
5 answers

, . - - , ??, :

return ((Depth - StartDepth) ?? Globals.StartDepth) * 
          PrintScale ?? Constants.YPixelsPerUnit;

, :

return (Depth - (StartDepth ?? Globals.StartDepth)) * 
          PrintScale ?? Constants.YPixelsPerUnit;

, :

double actualStartDepth = StartDepth ?? Globals.StartDepth;
double actualScale = PrintScale ?? Constants.YPixelsPerUnit;
return (depth - actualStartDepth) * actualScale;
+7

@Jon Skeet, . (, (Depth - (StartDepth ?? Globals.StartDepth)) * PrintScale ?? Constants.YPixelsPerUnit;)

, , , # .

" " . . :

, , . , , , 2 + 3 x 4 2 + (3 x 4), (2 + 3) x 4.

, , . , , a + b + c (a + b) + c, a + (b + c). ; . ( a, b, c , (a + b) + c a + (b + c) #?)

, . , ; " " #. , # " ".

+3

, . IIRC? ?? .

0

As can be seen from the priority order of various operators, zero coalescence is much lower than -or *.

0
source

I think this is a problem with parentheses .... Try the following:

public static double YFromDepth(double Depth, double? StartDepth, double? PrintScale)
{               
    return (Depth - (StartDepth ?? Globals.StartDepth)) * (PrintScale ?? Constants.YPixelsPerUnit) ;
}

NTN

0
source

All Articles