Visual Studio 2015 says that "casting is redundant." What for?

I have an image with a width of 888px and a height of 592px, with the aspect ratio of the width: height as 3: 2.

The following is an incorrect value of 1 due to integer calculation / truncation, both BitmapDecoder.PixelWidth and BitmapDecoder.PixelHeight are both uint (unsigned integer) and decoder below, which is a BitmapDecoder object.

double aspectRatio = decoder.PixelWidth / decoder.PixelHeight;

The following is the expected correct value of 1.5, but Visual Studio says "Cast is redundant", but why?

double aspectRatio = (double)decoder.PixelWidth / (double)decoder.PixelHeight;

+5
source share
2 answers

You just need to drop one of the uint to double the strength of the floating point arithmetic, either:

 double aspectRatio = decoder.PixelWidth / (double)decoder.PixelHeight; 

or

 double aspectRatio = (double)decoder.PixelWidth / decoder.PixelHeight; 

Personally, I would go with the latter, but this is a matter of opinion.

+12
source

Just to complement @ChrisF's answer, you can see this in IL code, where a single double tide will give a conversion for both values:

 IL_0013: stloc.0 // decoder IL_0014: ldloc.0 // decoder IL_0015: callvirt UserQuery+Decoder.get_PixelHeight IL_001A: conv.r.un // convert uint to float32 IL_001B: conv.r8 // convert to float64 (double) IL_001C: ldloc.0 // decoder IL_001D: callvirt UserQuery+Decoder.get_PixelWidth IL_0022: conv.r.un // convert uint to float32 IL_0023: conv.r8 // convert to float64 (double) 
+2
source

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


All Articles