Literals and implicit narrowing conversions

2019-07-13 09:09发布

问题:

a) Shouldn’t the following assignment cause an error, since number 100 is a literal of type int and since compiler doesn’t allow implicit narrowing conversions?

byte b = 100; 


b) If compiler doesn’t complain about implicit narrowing conversion from int literal to type byte, then why doesn’t it also allow an implicit narrowing conversion from double literal to type float ( I realize we could avoid this error by specifying float literal using F/f suffix )?

byte b=16; //OK
float f1=16.9; //error


thank you

回答1:

This is covered in section 6.1.8 of the C# language spec. It is legal for constant expressions of type int to be converted to sbyte, byte, short, ushort, uint or ulong provided the value is within the range of the target type. It is fairly easy for the C# compiler to determine if the value is within the appropriate range and hence allow the conversion.

As for the double case, the C# lang spec does not specifically call out why this is not allowed. My guess is it has to do with difficulties in determining if the double value can fit within the float value. Getting floating point precision correct is a very difficult task and probably so much so it wasn't deemed to be worth the cost (if it was possible at all)



标签: c# .net clr