Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this value conversion behavior change an expected change between .NET 8 and .NET 9?

Compile

if ((int)MathF.Floor(float.PositiveInfinity) > 0)
    Console.WriteLine("This is .NET 9.0");
else
    Console.WriteLine("This is .NET 8.0");

using either of these project files:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

or

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

On my computer, the program will correctly identify which project file you used, regardless of whether you compile it in debug or release mode.

The Watch window in VS 2022 (17.13.3) reports that (int)MathF.Floor(float.PositiveInfinity) is -2147483648 regardless of which runtime was targeted, but despite that, the > 0 branch is taken on .NET 9.

Dumping the two Release DLLs in ildasm shows no meaningful differences.

Environment.Version is 8.0.14 or 9.0.3.

Edits after the question was answered:
Yes, my computer is x86-64.
The VS Watch window does not (yet?) perform saturating conversions when debugging a .NET 9 application.

like image 277
DaleStan Avatar asked Sep 13 '25 13:09

DaleStan


1 Answers

This is related to this change, where all the floating-point-to-integer conversions now have saturating behaviour on x86/x64 machines.

Before the change, the result of converting a floating point number to int will always be int.MinValue as long as the value is outside of the range of int. After the change, the result will be int.MaxValue when the value is larger than int.MaxValue, and int.MinValue when the value is smaller than int.MinValue.

The reason for this change is

This change was made to standardize all floating point-to-integer conversions to have saturating behavior and to make the behavior deterministic.

Case in point: I cannot actually reproduce the behaviour in your code on an Apple M4 MacBook.

See also a similar issue reported on the GitHub repo.

like image 79
Sweeper Avatar answered Sep 15 '25 03:09

Sweeper