I don’t understand the casting rules when it comes to decimal and double.
It is legal to do this
decimal dec = 10;
double doub = (double) dec;
What confuses me however is that decimal is a 16 byte datatype and double is 8 bytes so isn’t casting a double to a decimal a widening conversation and should therefore be allowed implicitly; with the example above disallowed?
double doub = 3.2;
decimal dec = doub; // CS0029: Cannot implicitly convert type 'double' to 'decimal'
If you convert from
doubletodecimal, you can lose information – the number may be completely out of range, as the range of adoubleis much larger than the range of adecimal.If you convert from
decimaltodouble, you can lose information – for example, 0.1 is exactly representable indecimalbut not indouble, anddecimalactually uses a lot more bits for precision thandoubledoes.Implicit conversions shouldn’t lose information (the conversion from
longtodoublemight, but that’s a different argument). If you’re going to lose information, you should have to tell the compiler that you’re aware of that, via an explicit cast.That’s why there aren’t implicit conversions either way.