Explicit numeric conversion from float and double to any integral type described in the C# 5.0 specification (paragraph 6.2.1) as follows:
• For a conversion from float or double to an integral type, the processing depends on the overflow checking context (§7.6.12) in which the conversion takes place:
o In a checked context, the conversion proceeds as follows: • If the value of the operand is NaN or infinite, a System.OverflowException is thrown. • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion. • Otherwise, a System.OverflowException is thrown. o In an unchecked context, the conversion always succeeds, and proceeds as follows. • If the value of the operand is NaN or infinite, the result of the conversion is an unspecified value of the destination type. • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion. • Otherwise, the result of the conversion is an unspecified value of the destination type.
At the same time rules for same conversion described in the MSDN as follows:
When you convert from a double or float value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.
Evaluating of such conversion, for example "(int)123.566", gets us "123". Is description given in the specification correct?
Both descriptions in MSDN and C# 5.0 Specification are correct.
C# expressions are
unchecked
by default. Take a look at the bold part again;First, let's take a look what Specification says:
Let's analyze it on
number line
;As we can see, result will be 123 when we round towards zero.
Second, let's take a look what MSDN says:
From
Wikipedia
page;As we can see, result will be
123
when we truncate it also.