Why (int)double.NaN and (int)double.PositiveInfinity are 0?

c#

Solution

It depends on what kind of context you're in. If you use a `checked` context, you'll get an exception. The relevant section of the spec is section 6.2.1:

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:

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

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

So in an unchecked context, the answer isn't necessarily 0 - it's an unspecified `int` value. In fact, in my testing, it comes up as `int.MinValue` rather than 0 in an unchecked context.

But fundamentally, if you want to do checking, use a checked context (at least for that expression).

Problem

in C#, if you `0/0` you get an exception. But if you `0.0/0` or `0.0/0.0` you get `double.NaN` and `double.Infinity`, respectively. but if you cast these results to `int`, you get 0. ``` > (int)double.PositiveInfinity 0 > (int)double.NaN 0 ``` Why is this the case? Isn't the runtime supposed to give casting error because infinity is clearly not a zero?

Original source