views:

91

answers:

4

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?

+2  A: 

It's an explicit conversion (cast) that converts the result of the division operation to a long.

See: Casting and Type Conversions

NullUserException
A: 

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".

Adam
+4  A: 

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.

Chris Schmich
A: 

In my opinion there could be a few reasons:

  1. At least one of types in expression is not integer type (I don't think so).
  2. Developer wanted to highlighted that result is long type (makes the result type clear for reader -- good reason).
  3. Developer was not sure what is the result of expression and wanted to make sure it will be long (it's better to make sure, that hopes, it will work).

I believe it was 3 :).

Grzegorz Gierlik