In the following snippet:
long frameRate = (long)(_frameCounter / this._stopwatch.Elapsed.TotalSeconds);
Why is there an additional (long)(...) to the right of the assignment operator?
In the following snippet:
long frameRate = (long)(_frameCounter / this._stopwatch.Elapsed.TotalSeconds);
Why is there an additional (long)(...) to the right of the assignment operator?
It's an explicit conversion (cast) that converts the result of the division operation to a long
.
Because the result of the calculation relates to what types the variables are that are being used. If the compiler thinks the result type is not a long
because of the types being acted on, then you need to cast your result.
Note that casting your result may incur loss of accuracy or values. The bracketed cast (long)
is an explicit cast and will not generate any errors if, say, you tried to fit "1.234" into a long
, which could only store "1".
The division creates a double-precision floating point value (since TimeSpan.TotalSeconds
is a double
), so the cast truncates the resulting value to be integral instead of floating point. You end up with an approximate but whole number of frames-per-second instead of an exact answer with fractional frames-per-second.
If frameRate
is used for display or logging, the cast might just be to make the output look nicer.
In my opinion there could be a few reasons:
long
type (makes the result type clear for reader -- good reason).long
(it's better to make sure, that hopes, it will work).I believe it was 3 :).