できない.dev

.NET を 8 から 10 に上げると動かなくなること

.NET を 8 から 10 に上げると、System.Linq.Async を使うコードが CS0121 でビルドできなくなり、BinaryFormatter は設定で許可していても例外を投げる。
SDK だけを 10 にしたときの変化 2 つと、TargetFramework を net10.0 にしたときの変化 10 個を、同じコンテナで打ち比べた。

公開:

.NET 8 のサポートは 2026-11-10 に終わった。
8 と 10 はどちらも LTS で、このページは 9 を飛ばして 10 に上げる読者に向けて、9 で入った変更(BinaryFormatter・浮動小数点数の変換・X509Certificate2 のコンストラクター)も入れた。
TargetFramework を net8.0 から net10.0 に上げると、公式の表のとおり既定の言語バージョンも C# 12 から C# 14 に上がる(ページの URL の 8 と 10 は .NET の版で、C# の版ではない)。
公式イメージの .NET 10 SDK に dotnet-install.sh で .NET 8 SDK を足し、1 つのコンテナに並べて打ち比べた。
各節の出力は「v8 では」「v10 に上げると」「v10 で直すと」の 3 段で並ぶ。

変更点は、SDK を 10 にしただけで変わるもの(最初の 2 つ)と、プロジェクトの TargetFramework を net8.0 から net10.0 にすると変わるもの(残りの 10 個)に分かれる。
SDK の節は、旧版の段で global.json を使って SDK 8 に固定し、新版の段で global.json を消した。
プロジェクトは net8.0 のままで、global.json が無ければ入っているいちばん新しい SDK 10 が使われる。
TargetFramework の節は、どの段も SDK 10 で打ち、旧版の段を net8.0、新版の段を net10.0 にした。
旧版の段(SDK 10 と net8.0)では 10 個とも新版の段の変化が出なかったので、この 10 個は SDK 10 を入れただけでは起きない。

global.json が要求する版の SDK が入っていないときのエラーと直し方は、「A compatible .NET SDK was not found」の記事にまとめた。

公式の一覧には、ほかにも次のような変更がある。
どれもこのページでは打っていない。
一覧はこれで全部ではなく、ここに挙げていない変更も公式の一覧にある。

  • Windows だけの変更(Windows Forms と WPF の変更、CET の既定の有効化、Windows の秘密鍵の扱い)。
  • Visual Studio に関わる変更(.NET 9 SDK が求める Visual Studio と MSBuild の版)。
  • .NET 9 SDK で Terminal Logger が既定になった。
    公式によると、出力をリダイレクトしたときは使われない。
    このページの出力はリダイレクトして取ったので、従来の形で出ている。
  • 公式のコンテナイメージの既定が Ubuntu になった(このページのコンテナも Ubuntu 24.04 だった)。
  • SDK とランタイムの細かな変更(Unix の名前付きミューテックスの既定のスコープ、dotnet コマンドが本筋でない出力を標準エラーに出す変更、--interactive の既定、DefineConstants を評価する時期)。
  • .NET 10 で非推奨になったほかの API。
    SslStream の暗号の情報を返すプロパティ(SYSLIB0058)と、SystemEvents.EventsThreadShutdown(SYSLIB0059)がある。
    IComparer<TSource> を取る Queryable.MaxBy と MinBy(SYSLIB0061)、XsltSettings.EnableScript(SYSLIB0062)も非推奨になった。
  • Microsoft.Extensions の変更(構成の null の値が保たれる、BackgroundService が ExecuteAsync の全体を Task として走らせる)と、ASP.NET Core・EF Core の変更(それぞれ別の一覧がある)。

dotnet new sln が .slnx を作るようになった

SDK 10 の dotnet new sln は、XML で書く新しい形式の .slnx を作る。
SDK 8 では .sln を作っていた。
TargetFramework には関係なく、SDK を 10 にした時点で変わる。
ここでは src/App/App.csproj を置いたディレクトリでソリューションを作り、プロジェクトを足した。

v8 では

$ cat global.json
{
  "sdk": {
    "version": "8.0.428"
  }
}
$ dotnet new sln -n App
The template "Solution File" was created successfully.
$ ls
App.sln
global.json
src
$ dotnet sln App.sln add src/App/App.csproj
Project `src/App/App.csproj` added to the solution.
$ echo $?
0

v10 に上げると

$ rm App.sln global.json
$ dotnet --version
10.0.404
$ dotnet new sln -n App
The template "Solution File" was created successfully.
$ ls
App.slnx
src
$ dotnet sln App.sln add src/App/App.csproj
Could not find solution or directory `App.sln`.
$ echo $?
1

v10 で直すと

$ dotnet sln App.slnx add src/App/App.csproj
Project `src/App/App.csproj` added to the solution.
$ echo $?
0
$ cat App.slnx
<Solution>
  <Folder Name="/src/">
    <Project Path="src/App/App.csproj" />
  </Folder>
</Solution>
$ rm App.slnx
$ dotnet new sln -n App --format sln
The template "Solution File" was created successfully.
$ dotnet sln App.sln add src/App/App.csproj
Project `src/App/App.csproj` added to the solution.
$ echo $?
0

App.sln という名前を前提にしたスクリプトや CI は、dotnet sln App.slnx add のように拡張子を .slnx に書き換える。
今までどおり .sln を作るなら、dotnet new sln --format sln を打つ。
公式によると、SDK が .slnx に対応したのは 9.0.200 からである。
SDK 8 でもビルドするリポジトリなら、--format sln で作っておく(SDK 8 に .slnx を読ませるのは打っていない)。

版を書かない PackageReference がエラー NU1015 になった

Version を書かない <PackageReference> は、SDK 8 では警告 NU1604 を出して、そのパッケージのいちばん古い版を入れていた。
SDK 10 の restore は、エラー NU1015 で止まる。
TargetFramework は net8.0 のままで、SDK だけを 10 にした。

v8 では

$ cat global.json
{
  "sdk": {
    "version": "8.0.428"
  }
}
$ grep PackageReference App.csproj
    <PackageReference Include="Newtonsoft.Json" />
$ dotnet restore
  Determining projects to restore...
/app/packageref-version/App.csproj : warning NU1604: Project dependency Newtonsoft.Json does not contain an inclusive lower bound. Include a lower bound in the dependency version to ensure consistent restore results.
/app/packageref-version/App.csproj : warning NU1903: Package 'Newtonsoft.Json' 3.5.8 has a known high severity vulnerability, https://github.com/advisories/GHSA-5crp-9r3c-p9vr
/app/packageref-version/App.csproj : warning NU1701: Package 'Newtonsoft.Json 3.5.8' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net8.0'. This package may not be fully compatible with your project.
  Restored /app/packageref-version/App.csproj (in 2.01 sec).
$ echo $?
0

v10 に上げると

$ rm global.json
$ dotnet --version
10.0.404
$ dotnet restore
  Determining projects to restore...
/app/packageref-version/App.csproj : error NU1015: The following PackageReference item(s) do not have a version specified: Newtonsoft.Json
  Failed to restore /app/packageref-version/App.csproj (in 45 ms).
$ echo $?
1

v10 で直すと

$ grep PackageReference App.csproj
    <PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
$ dotnet restore
  Determining projects to restore...
  Restored /app/packageref-version/App.csproj (in 999 ms).
$ echo $?
0

SDK 8 の段では Newtonsoft.Json のいちばん古い 3.5.8 が入り、脆弱性の警告 NU1903 と、.NET Framework 向けのパッケージを使った警告 NU1701 も出ていた。
版を書けば、SDK 10 でも restore が通る。
公式は、いちばん古い版を入れたいなら Version="0.0.0" と書く方法と、SdkAnalysisLevel を 9.0.300 以下にして元の警告に戻す方法も挙げている(どちらも打っていない)。
公式によると、Central Package Management で版を別のファイルに書いているプロジェクトは変わらない。

BinaryFormatter が設定で許可していても例外を投げるようになった

.NET 9 で、標準の BinaryFormatter は中身が取り除かれ、どの設定でも例外を投げるようになった。
旧版の段のプロジェクトは、EnableUnsafeBinaryFormatterSerialization を true にし、警告 SYSLIB0011 を NoWarn で抑えている。
この設定のまま、文字列のリストを BinaryFormatter で書いて読み戻した。

v8 では

$ dotnet --version
10.0.404
$ grep -E "TargetFramework|EnableUnsafeBinaryFormatterSerialization|NoWarn" App.csproj
    <TargetFramework>net8.0</TargetFramework>
    <EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>
    <NoWarn>$(NoWarn);SYSLIB0011</NoWarn>
$ cat Program.cs
using System.Runtime.Serialization.Formatters.Binary;
 
var formatter = new BinaryFormatter();
using var stream = new MemoryStream();
formatter.Serialize(stream, new List<string> { "apple", "banana" });
stream.Position = 0;
var items = (List<string>)formatter.Deserialize(stream);
Console.WriteLine(string.Join(",", items));
$ dotnet run
apple,banana
$ echo $?
0

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet run
Unhandled exception. System.PlatformNotSupportedException: BinaryFormatter serialization and deserialization have been removed. See https://aka.ms/binaryformatter for more information.
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph)
   at Program.<Main>$(String[] args) in /app/binaryformatter/Program.cs:line 5
$ echo $?
134

v10 で直すと

$ grep PackageReference App.csproj
    <PackageReference Include="System.Runtime.Serialization.Formatters" Version="10.0.15" />
$ dotnet run
apple,banana
$ echo $?
0
$ cat Program.cs
using System.Text.Json;
 
var json = JsonSerializer.Serialize(new List<string> { "apple", "banana" });
Console.WriteLine(json);
var items = JsonSerializer.Deserialize<List<string>>(json)!;
Console.WriteLine(string.Join(",", items));
$ dotnet run
["apple","banana"]
apple,banana
$ echo $?
0

net10.0 では、Serialize を呼んだ時点で PlatformNotSupportedException が出た。

すぐに動かしたいだけなら、別パッケージの System.Runtime.Serialization.Formatters の PackageReference を csproj に足す。
net10.0 でも同じ出力になった。
破壊的変更のページは「設定も取り除かれた」と書くが、公式の移行ガイドは、このパッケージを使うときも EnableUnsafeBinaryFormatterSerialization を true にするよう書いている。
ここでも csproj に残したまま打った(外した場合は打っていない)。

公式はこのパッケージをサポート外で安全でないとしていて、BinaryFormatter から離れるよう強く勧めている。
続けて使うコードは、System.Text.Json などの別の形式に移す。

System.Linq.Async の LINQ が標準のものとぶつかり CS0121 になった

.NET 10 は、IAsyncEnumerable<T> 用の LINQ(Where や ToListAsync)を標準の System.Linq.AsyncEnumerable クラスに入れた。
.NET 9 までは、コミュニティの System.Linq.Async パッケージが、同じ名前のクラスで提供していた。
両方があると同じ呼び出しに候補が 2 つ見つかり、CS0121 でビルドが止まる。
ここでは System.Linq.Async 6.0.3 を入れたプロジェクトで、Where と SelectAwait を使った。

v8 では

$ dotnet --version
10.0.404
$ grep -E "TargetFramework|PackageReference" App.csproj
    <TargetFramework>net8.0</TargetFramework>
    <PackageReference Include="System.Linq.Async" Version="6.0.3" />
$ cat Program.cs
var evens = await Numbers().Where(n => n % 2 == 0).ToListAsync();
Console.WriteLine(string.Join(",", evens));
 
var doubled = await Numbers().SelectAwait(async n => { await Task.Yield(); return n * 2; }).ToListAsync();
Console.WriteLine(string.Join(",", doubled));
 
static async IAsyncEnumerable<int> Numbers()
{
    for (var i = 1; i <= 6; i++)
    {
        await Task.Yield();
        yield return i;
    }
}
$ dotnet run
2,4,6
2,4,6,8,10,12
$ echo $?
0

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet run
/app/linq-async/Program.cs(1,29): error CS0121: The call is ambiguous between the following methods or properties: 'System.Linq.AsyncEnumerable.Where<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Func<TSource, bool>) [/root/.nuget/packages/system.linq.async/6.0.3/ref/net6.0/System.Linq.Async.dll]' and 'System.Linq.AsyncEnumerable.Where<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Func<TSource, bool>) [/usr/share/dotnet/packs/Microsoft.NETCore.App.Ref/10.0.15/ref/net10.0/System.Linq.AsyncEnumerable.dll]' [/app/linq-async/App.csproj]
/app/linq-async/Program.cs(4,93): error CS0121: The call is ambiguous between the following methods or properties: 'System.Linq.AsyncEnumerable.ToListAsync<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Threading.CancellationToken) [/root/.nuget/packages/system.linq.async/6.0.3/ref/net6.0/System.Linq.Async.dll]' and 'System.Linq.AsyncEnumerable.ToListAsync<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Threading.CancellationToken) [/usr/share/dotnet/packs/Microsoft.NETCore.App.Ref/10.0.15/ref/net10.0/System.Linq.AsyncEnumerable.dll]' [/app/linq-async/App.csproj]
 
The build failed. Fix the build errors and run again.
$ echo $?
1

v10 で直すと

$ dotnet remove package System.Linq.Async
info : Removing PackageReference for package 'System.Linq.Async' from project '/app/linq-async/App.csproj'.
$ dotnet run
/app/linq-async/Program.cs(4,31): error CS1061: 'IAsyncEnumerable<int>' does not contain a definition for 'SelectAwait' and no accessible extension method 'SelectAwait' accepting a first argument of type 'IAsyncEnumerable<int>' could be found (are you missing a using directive or an assembly reference?) [/app/linq-async/App.csproj]
 
The build failed. Fix the build errors and run again.
$ echo $?
1
$ cat Program.cs
var evens = await Numbers().Where(n => n % 2 == 0).ToListAsync();
Console.WriteLine(string.Join(",", evens));
 
var doubled = await Numbers().Select(async (int n, CancellationToken ct) => { await Task.Yield(); return n * 2; }).ToListAsync();
Console.WriteLine(string.Join(",", doubled));
 
static async IAsyncEnumerable<int> Numbers()
{
    for (var i = 1; i <= 6; i++)
    {
        await Task.Yield();
        yield return i;
    }
}
$ dotnet run
2,4,6
2,4,6,8,10,12
$ echo $?
0

直すときは、System.Linq.Async の参照を消す。
標準の LINQ には SelectAwait が無いので、消した直後は CS1061 で止まった。
公式のとおり、Select に async (int n, CancellationToken ct) => … を渡す形に書き換えると通った。
公式は、System.Linq.Async を 7.0.0 に上げる方法と、ほかのパッケージ経由で入ってくるときに ExcludeAssets で外す方法も挙げている。
net10.0 と古い TargetFramework の両方を対象にするプロジェクトなら、System.Linq.Async の代わりに System.Linq.AsyncEnumerable パッケージを参照する、と公式は書いている(どれも打っていない)。

依存の依存にある脆弱性も restore が警告するようになった

NuGet の脆弱性の検査(NuGetAudit)は、公式によると net8.0 のプロジェクトでは直接参照したパッケージだけを見る。
net10.0 にすると NuGetAuditMode の既定が all になり、依存の依存(推移的なパッケージ)も見る。
ここでは Newtonsoft.Json.Bson 1.0.2 だけを参照した。
このパッケージが Newtonsoft.Json 12.0.1 を連れてくる。

v8 では

$ dotnet --version
10.0.404
$ grep -E "TargetFramework|PackageReference" App.csproj
    <TargetFramework>net8.0</TargetFramework>
    <PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" />
$ dotnet build
  Determining projects to restore...
  Restored /app/nuget-audit-transitive/App.csproj (in 185 ms).
  App -> /app/nuget-audit-transitive/bin/Debug/net8.0/App.dll
 
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.98
$ echo $?
0
$ dotnet list package --include-transitive
  Determining projects to restore...
  All projects are up-to-date for restore.
Project 'App' has the following package references
   [net8.0]: 
   Top-level Package           Requested   Resolved
   > Newtonsoft.Json.Bson      1.0.2       1.0.2   
 
   Transitive Package      Resolved
   > Newtonsoft.Json       12.0.1

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet build
  Determining projects to restore...
/app/nuget-audit-transitive/App.csproj : warning NU1903: Package 'Newtonsoft.Json' 12.0.1 has a known high severity vulnerability, https://github.com/advisories/GHSA-5crp-9r3c-p9vr
  Restored /app/nuget-audit-transitive/App.csproj (in 211 ms).
/app/nuget-audit-transitive/App.csproj : warning NU1903: Package 'Newtonsoft.Json' 12.0.1 has a known high severity vulnerability, https://github.com/advisories/GHSA-5crp-9r3c-p9vr
  App -> /app/nuget-audit-transitive/bin/Debug/net10.0/App.dll
 
Build succeeded.
 
/app/nuget-audit-transitive/App.csproj : warning NU1903: Package 'Newtonsoft.Json' 12.0.1 has a known high severity vulnerability, https://github.com/advisories/GHSA-5crp-9r3c-p9vr
/app/nuget-audit-transitive/App.csproj : warning NU1903: Package 'Newtonsoft.Json' 12.0.1 has a known high severity vulnerability, https://github.com/advisories/GHSA-5crp-9r3c-p9vr
    2 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:01.06
$ echo $?
0

v10 で直すと

$ dotnet nuget why Newtonsoft.Json
Project 'App' has the following dependency graph(s) for 'Newtonsoft.Json':
 
  [net10.0]                                                                     
  └── Newtonsoft.Json.Bson (v1.0.2)                                             
      └── Newtonsoft.Json (v12.0.1)
$ grep PackageReference App.csproj
    <PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
    <PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" />
$ dotnet build
  Determining projects to restore...
  All projects are up-to-date for restore.
  App -> /app/nuget-audit-transitive/bin/Debug/net10.0/App.dll
 
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.88
$ echo $?
0

net8.0 の段では、12.0.1 が入っていても警告は出なかった。
net10.0 では NU1903 の警告が出る。
ビルドは通るが、警告をエラーとして扱うプロジェクトでは restore が失敗する、と公式は書いている(打っていない)。

dotnet nuget why を打つと、どのパッケージが連れてきたかが分かる。
連れてきた側を上げても直らなければ、脆弱性の直った版を直接参照する。
ここでは Newtonsoft.Json 13.0.4 の PackageReference を csproj に足して、警告が消えた。
前と同じく直接参照だけを見たいなら、<NuGetAuditMode>direct</NuGetAuditMode> を書く(打っていない)。

.NET に含まれるパッケージを参照すると NU1510 の警告が出るようになった

System.Text.Json は .NET の標準ライブラリに入っているが、NuGet のパッケージとしても配られている。
net10.0 では、フレームワークに含まれるパッケージを直接参照していると、NuGet が警告 NU1510 を出す。
ここでは net8.0 のプロジェクトで System.Text.Json 8.0.6 を参照していた。

v8 では

$ dotnet --version
10.0.404
$ grep -E "TargetFramework|PackageReference" App.csproj
    <TargetFramework>net8.0</TargetFramework>
    <PackageReference Include="System.Text.Json" Version="8.0.6" />
$ dotnet build
  Determining projects to restore...
  Restored /app/nu1510-pruned/App.csproj (in 163 ms).
  App -> /app/nu1510-pruned/bin/Debug/net8.0/App.dll
 
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.89
$ echo $?
0

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet build
  Determining projects to restore...
/app/nu1510-pruned/App.csproj : warning NU1510: PackageReference System.Text.Json will not be pruned. This package is automatically available and does not need to be referenced explicitly. Remove the PackageReference item.
  Restored /app/nu1510-pruned/App.csproj (in 213 ms).
/app/nu1510-pruned/App.csproj : warning NU1510: PackageReference System.Text.Json will not be pruned. This package is automatically available and does not need to be referenced explicitly. Remove the PackageReference item.
  App -> /app/nu1510-pruned/bin/Debug/net10.0/App.dll
 
Build succeeded.
 
/app/nu1510-pruned/App.csproj : warning NU1510: PackageReference System.Text.Json will not be pruned. This package is automatically available and does not need to be referenced explicitly. Remove the PackageReference item.
/app/nu1510-pruned/App.csproj : warning NU1510: PackageReference System.Text.Json will not be pruned. This package is automatically available and does not need to be referenced explicitly. Remove the PackageReference item.
    2 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:01.01
$ echo $?
0

v10 で直すと

$ dotnet remove package System.Text.Json
info : Removing PackageReference for package 'System.Text.Json' from project '/app/nu1510-pruned/App.csproj'.
$ dotnet build
  Determining projects to restore...
  Restored /app/nu1510-pruned/App.csproj (in 77 ms).
  App -> /app/nu1510-pruned/bin/Debug/net10.0/App.dll
 
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.80
$ echo $?
0

警告の文面のとおり、このパッケージは参照しなくても使えるので、直すときは参照を消す。
net8.0 と net10.0 の両方を対象にするプロジェクトなら、公式は Condition で古い TargetFramework のときだけ参照する書き方を示している(打っていない)。

X509Certificate2 のコンストラクターで証明書を読むと SYSLIB0057 の警告が出るようになった

.NET 9 から、ファイルやバイト列から証明書を読む X509Certificate2 と X509Certificate のコンストラクターが非推奨になった。
公式によると、渡された中身の形式を決めずに X.509 も PKCS12(PFX)も読んでしまうのが理由である。
ここでは openssl で作った PFX ファイルを、パスワードつきで読んだ。

v8 では

$ dotnet --version
10.0.404
$ cat Program.cs
using System.Security.Cryptography.X509Certificates;
 
using var cert = new X509Certificate2("cert.pfx", "secret");
Console.WriteLine(cert.Subject);
$ dotnet build
  Determining projects to restore...
  All projects are up-to-date for restore.
  App -> /app/x509-loader/bin/Debug/net8.0/App.dll
 
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.75
$ echo $?
0

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet build
  Determining projects to restore...
  Restored /app/x509-loader/App.csproj (in 63 ms).
/app/x509-loader/Program.cs(3,18): warning SYSLIB0057: 'X509Certificate2.X509Certificate2(string, string?)' is obsolete: 'Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates.' (https://aka.ms/dotnet-warnings/SYSLIB0057) [/app/x509-loader/App.csproj]
  App -> /app/x509-loader/bin/Debug/net10.0/App.dll
 
Build succeeded.
 
/app/x509-loader/Program.cs(3,18): warning SYSLIB0057: 'X509Certificate2.X509Certificate2(string, string?)' is obsolete: 'Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates.' (https://aka.ms/dotnet-warnings/SYSLIB0057) [/app/x509-loader/App.csproj]
    1 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.97
$ echo $?
0
$ dotnet run
CN=example.test
$ echo $?
0

v10 で直すと

$ cat Program.cs
using System.Security.Cryptography.X509Certificates;
 
using var cert = X509CertificateLoader.LoadPkcs12FromFile("cert.pfx", "secret");
Console.WriteLine(cert.Subject);
$ dotnet build
  Determining projects to restore...
  All projects are up-to-date for restore.
  App -> /app/x509-loader/bin/Debug/net10.0/App.dll
 
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.67
$ echo $?
0
$ dotnet run
CN=example.test
$ echo $?
0

警告が出るだけで、net10.0 でも証明書は読めた。
直すときは、.NET 9 で入った X509CertificateLoader の、形式ごとのメソッドに替える。
PFX なら LoadPkcs12FromFile、X.509 の証明書なら LoadCertificateFromFile を使う(後者は打っていない)。
公式によると、.NET Framework と .NET Standard では Microsoft.Bcl.Cryptography パッケージが X509CertificateLoader を足す。

Rfc2898DeriveBytes のコンストラクターに SYSLIB0060 の警告が出るようになった

.NET 10 から、PBKDF2 で鍵やパスワードのハッシュを作る Rfc2898DeriveBytes のコンストラクターがすべて非推奨になった。
公式によると、インスタンスの GetBytes を何度も呼んで続きのバイト列を取り出せる使い方が、PBKDF2 の本来の使い方から外れているのが理由である。
1 回で計算する静的メソッド Pbkdf2 に移す。
ここでは SHA-256 と 100,000 回の繰り返しで 32 バイトを作った。

v8 では

$ dotnet --version
10.0.404
$ cat Program.cs
using System.Security.Cryptography;
 
byte[] salt = Convert.FromHexString("00112233445566778899AABBCCDDEEFF");
using var kdf = new Rfc2898DeriveBytes("p@ssw0rd", salt, 100_000, HashAlgorithmName.SHA256);
Console.WriteLine(Convert.ToHexString(kdf.GetBytes(32)));
$ dotnet build
  Determining projects to restore...
  All projects are up-to-date for restore.
  App -> /app/rfc2898-pbkdf2/bin/Debug/net8.0/App.dll
 
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.77
$ echo $?
0
$ dotnet run
33894AD87EACD32DF4A5BB3F2EFD6DC257F2E9795FCB1A2E6864C61BBA22A78D

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet build
  Determining projects to restore...
  Restored /app/rfc2898-pbkdf2/App.csproj (in 59 ms).
/app/rfc2898-pbkdf2/Program.cs(4,17): warning SYSLIB0060: 'Rfc2898DeriveBytes.Rfc2898DeriveBytes(string, byte[], int, HashAlgorithmName)' is obsolete: 'The constructors on Rfc2898DeriveBytes are obsolete. Use the static Pbkdf2 method instead.' (https://aka.ms/dotnet-warnings/SYSLIB0060) [/app/rfc2898-pbkdf2/App.csproj]
  App -> /app/rfc2898-pbkdf2/bin/Debug/net10.0/App.dll
 
Build succeeded.
 
/app/rfc2898-pbkdf2/Program.cs(4,17): warning SYSLIB0060: 'Rfc2898DeriveBytes.Rfc2898DeriveBytes(string, byte[], int, HashAlgorithmName)' is obsolete: 'The constructors on Rfc2898DeriveBytes are obsolete. Use the static Pbkdf2 method instead.' (https://aka.ms/dotnet-warnings/SYSLIB0060) [/app/rfc2898-pbkdf2/App.csproj]
    1 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.82
$ echo $?
0
$ dotnet run
33894AD87EACD32DF4A5BB3F2EFD6DC257F2E9795FCB1A2E6864C61BBA22A78D

v10 で直すと

$ cat Program.cs
using System.Security.Cryptography;
 
byte[] salt = Convert.FromHexString("00112233445566778899AABBCCDDEEFF");
byte[] key = Rfc2898DeriveBytes.Pbkdf2("p@ssw0rd", salt, 100_000, HashAlgorithmName.SHA256, 32);
Console.WriteLine(Convert.ToHexString(key));
$ dotnet build
  Determining projects to restore...
  All projects are up-to-date for restore.
  App -> /app/rfc2898-pbkdf2/bin/Debug/net10.0/App.dll
 
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.72
$ echo $?
0
$ dotnet run
33894AD87EACD32DF4A5BB3F2EFD6DC257F2E9795FCB1A2E6864C61BBA22A78D

net10.0 では SYSLIB0060 の警告が出るが、出力は net8.0 と同じだった。
Rfc2898DeriveBytes.Pbkdf2 に同じパスワード・ソルト・回数・ハッシュと長さを渡すと、警告が消えて同じ値が出た。
保存済みのハッシュと照らし合わせるコードも、引数を揃えれば書き換えたあとに同じ値で比べられる。

ソルトの長さだけを渡すコンストラクターを使っていたなら、公式によると Pbkdf2 には長さを取る形が無い。
RandomNumberGenerator.GetBytes でソルトを作ってから渡す(打っていない)。

SIGTERM を受けたときに ProcessExit が走らなくなった

.NET 8 のランタイムは、SIGTERM を受けると AppDomain.ProcessExit を起こしてから終了していた。
.NET 10 のランタイムは SIGTERM の受け口を自分で用意しなくなり、OS の既定のまま、その場で終了する。
Docker のドキュメントによると、docker stop もコンテナのメインのプロセスに SIGTERM を送る(Docker では打っていない)。
ここでは ProcessExit で 1 行書くだけのアプリを起動し、kill -TERM を送った。

v8 では

$ dotnet --version
10.0.404
$ cat Program.cs
AppDomain.CurrentDomain.ProcessExit += (_, _) => Console.WriteLine("ProcessExit: cleanup done");
Console.WriteLine("started");
Thread.Sleep(Timeout.Infinite);
$ dotnet build -v q
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.73
$ bin/Debug/net8.0/App > app.log &
$ kill -TERM $!
$ wait $!
$ echo $?
143
$ cat app.log
started
ProcessExit: cleanup done

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet build -v q
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.80
$ bin/Debug/net10.0/App > app.log &
$ kill -TERM $!
$ wait $!
Terminated
$ echo $?
143
$ cat app.log
started

v10 で直すと

$ cat Program.cs
using System.Runtime.InteropServices;
 
using var sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, _ => Environment.Exit(0));
AppDomain.CurrentDomain.ProcessExit += (_, _) => Console.WriteLine("ProcessExit: cleanup done");
Console.WriteLine("started");
Thread.Sleep(Timeout.Infinite);
$ dotnet build -v q
Build succeeded.
    0 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:00.67
$ bin/Debug/net10.0/App > app.log &
$ kill -TERM $!
$ wait $!
$ echo $?
0
$ cat app.log
started
ProcessExit: cleanup done

net8.0 では ProcessExit の行が出て、終了コードは 143 だった。
net10.0 では ProcessExit が走らず、ログは started だけで終わった。
net10.0 の段だけ、シェルが Terminated と出している。
終了コードはどちらも 143 なので、終了コードを見るだけでは違いに気づけない。

直すときは、公式のとおり PosixSignalRegistration.Create で SIGTERM を受け、Environment.Exit(0) を呼ぶ。
ProcessExit が走り、終了コードは 0 になった。
公式によると、ASP.NET Core のアプリや UseConsoleLifetime などのホストを使うアプリは、ホストが SIGTERM を受けるので手当ては要らない(打っていない)。
公式によると Windows でも、コンソールを閉じたときとシャットダウンのときの通知で同じ変更が入った(打っていない)。

範囲外の浮動小数点数を整数にした結果が変わった

.NET 9 から、x86 と x64 では double や float を整数に変換するとき、型に入らない値を最大値か最小値に張り付ける(飽和させる)。
例外もエラーも出ないので、変わるのは結果の数値だけである。
ここでは x86_64 のコンテナで、3e9・-1.0・NaN を int・uint・long に変換した。

v8 では

$ uname -m
x86_64
$ dotnet --version
10.0.404
$ cat Program.cs
double[] values = [3e9, -1.0, double.NaN];
foreach (var v in values)
{
    Console.WriteLine($"{v}: (int)={(int)v} (uint)={(uint)v} (long)={(long)v}");
}
$ dotnet run
3000000000: (int)=-2147483648 (uint)=3000000000 (long)=3000000000
-1: (int)=-1 (uint)=4294967295 (long)=-1
NaN: (int)=-2147483648 (uint)=0 (long)=-9223372036854775808
$ echo $?
0

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet run
3000000000: (int)=2147483647 (uint)=3000000000 (long)=3000000000
-1: (int)=-1 (uint)=0 (long)=-1
NaN: (int)=0 (uint)=0 (long)=0
$ echo $?
0

v10 で直すと

$ cat Program.cs
double[] values = [3e9, -1.0, double.NaN];
foreach (var v in values)
{
    if (double.IsNaN(v) || v < int.MinValue || v > int.MaxValue)
    {
        Console.WriteLine($"{v}: out of range for int");
        continue;
    }
    Console.WriteLine($"{v}: (int)={(int)v}");
}
$ dotnet run
3000000000: out of range for int
-1: (int)=-1
NaN: out of range for int
$ echo $?
0

net8.0 で -2147483648 になっていた 3e9 の int は、net10.0 では 2147483647 になった。
-1.0 の uint は 4294967295 から 0 に、NaN の int と long は最小値から 0 になった。
範囲外の値が来うるコードは、変換の前に範囲と NaN を確かめる。
公式によると、この変更は x86 と x64 のもので、Arm64 は以前から別の結果を出していた(Arm64 は打っていない)。

プロパティの中の field が自動で作られるフィールドを指すようになった

C# 14 では、プロパティのアクセサーの中に書いた field が、コンパイラーが作る裏のフィールドを指すキーワードになった。
net10.0 の既定の言語バージョンは C# 14 なので、field という名前のメンバーを持つクラスでは、アクセサーの中に書いた field の意味が変わる(メソッドの中の field は変わらない)。
ここでは field というフィールドを、Count の get で返すクラスを使った。

v8 では

$ dotnet --version
10.0.404
$ cat Program.cs
var counter = new Counter();
counter.Increment();
Console.WriteLine(counter.Count);
 
class Counter
{
    private int field = 10;
 
    public int Count
    {
        get { return field; }
    }
 
    public void Increment() => field++;
}
$ dotnet run
11
$ echo $?
0

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet build
  Determining projects to restore...
  Restored /app/field-keyword/App.csproj (in 68 ms).
/app/field-keyword/Program.cs(11,22): warning CS9258: In language version 14.0, the 'field' keyword binds to a synthesized backing field for the property. To avoid generating a synthesized backing field, and to refer to the existing member, use 'this.field' or '@field' instead. [/app/field-keyword/App.csproj]
  App -> /app/field-keyword/bin/Debug/net10.0/App.dll
 
Build succeeded.
 
/app/field-keyword/Program.cs(11,22): warning CS9258: In language version 14.0, the 'field' keyword binds to a synthesized backing field for the property. To avoid generating a synthesized backing field, and to refer to the existing member, use 'this.field' or '@field' instead. [/app/field-keyword/App.csproj]
    1 Warning(s)
    0 Error(s)
 
Time Elapsed 00:00:01.52
$ echo $?
0
$ dotnet run
0
$ echo $?
0

v10 で直すと

$ grep -n this.field Program.cs
11:        get { return this.field; }
$ dotnet run
11
$ echo $?
0

net8.0 では、Increment で増やした 11 が出た。
net10.0 では警告 CS9258 が出てもビルドは通り、Count は 0 を返した。
メソッド Increment の中の field++ は元のフィールドを増やし続けるが、get の field は自動で作られた別のフィールドを読むようになったためである。

直すときは this.field か @field と書くか、フィールドの名前を変える。
警告の文面も同じ直し方を挙げている。
公式によると、アクセサーの中で field という名前のローカル変数を宣言すると、C# 14 ではエラー CS9272 になる(打っていない)。

式ツリーの中の配列の Contains が MemoryExtensions に結び付くようになった

C# 14 は、配列から Span<T> や ReadOnlySpan<T> への暗黙の変換を言語に組み込んだ。
そのため、配列に対して span を受け取るオーバーロードや拡張メソッドが選ばれる場面が増えた。
式ツリー(Expression<Func<…>>)の中で配列の Contains を呼ぶと、C# 12 では Enumerable.Contains に結び付いていたものが、MemoryExtensions.Contains に結び付く。
ここでは結び付いた先のクラスを出してから、式を解釈実行(Compile(preferInterpretation: true))した。

v8 では

$ dotnet --version
10.0.404
$ cat Program.cs
using System.Linq.Expressions;
 
Expression<Func<int[], int, bool>> contains = (array, n) => array.Contains(n);
Console.WriteLine(((MethodCallExpression)contains.Body).Method.DeclaringType);
var f = contains.Compile(preferInterpretation: true);
Console.WriteLine(f([1, 2, 3], 2));
$ dotnet run
System.Linq.Enumerable
True
$ echo $?
0

v10 に上げると

$ sed -i s/net8.0/net10.0/ App.csproj
$ dotnet run
System.MemoryExtensions
Unhandled exception. System.ArgumentException: GenericArguments[1], 'System.ReadOnlySpan`1[System.Int32]', on 'System.Linq.Expressions.Interpreter.FuncCallInstruction`2[T0,TRet]' violates the constraint of type 'TRet'.
 ---> System.TypeLoadException: GenericArguments[1], 'System.ReadOnlySpan`1[System.Int32]', on 'System.Linq.Expressions.Interpreter.FuncCallInstruction`2[T0,TRet]' violates the constraint of type parameter 'TRet'.
   at System.RuntimeTypeHandle.Instantiate(Type[] inst)
   at System.RuntimeType.MakeGenericType(Type[] typeArguments)
   --- End of inner exception stack trace ---
   at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
   at System.RuntimeType.MakeGenericType(Type[] typeArguments)
   at System.Linq.Expressions.Interpreter.CallInstruction.GetHelperType(MethodInfo info, Type[] arrTypes)
   at System.Linq.Expressions.Interpreter.CallInstruction.SlowCreate(MethodInfo info, ParameterInfo[] pis)
   at System.Linq.Expressions.Interpreter.CallInstruction.Create(MethodInfo info, ParameterInfo[] parameters)
   at System.Linq.Expressions.Interpreter.LightCompiler.CompileMethodCallExpression(Expression object, MethodInfo method, IArgumentProvider arguments)
   at System.Linq.Expressions.Interpreter.LightCompiler.CompileMethodCallExpression(Expression object, MethodInfo method, IArgumentProvider arguments)
   at System.Linq.Expressions.Interpreter.LightCompiler.Compile(Expression expr)
   at System.Linq.Expressions.Interpreter.LightCompiler.CompileTop(LambdaExpression node)
   at System.Linq.Expressions.Expression`1.Compile(Boolean preferInterpretation)
   at Program.<Main>$(String[] args) in /app/span-overload/Program.cs:line 5
$ echo $?
134

v10 で直すと

$ grep -n Enumerable.Contains Program.cs
3:Expression<Func<int[], int, bool>> contains = (array, n) => Enumerable.Contains(array, n);
$ dotnet run
System.Linq.Enumerable
True
$ echo $?
0

net8.0 では System.Linq.Enumerable に結び付き、True が出た。
net10.0 では System.MemoryExtensions に結び付き、Compile を呼んだ時点で ArgumentException が出た。
直すときは、公式のとおり Enumerable.Contains(array, n) と呼び出し先を書く。
AsEnumerable() を挟むか IEnumerable<int> にキャストしても、Enumerable.Contains に結び付く、と公式は書いている(打っていない)。

公式は、この変更で起きることをほかに 2 つ挙げている(どちらも打っていない)。
1 つは、配列を渡す呼び出しで span のオーバーロードも候補に入り、どれを選ぶか決まらずにコンパイルエラーになることで、xUnit の Assert.Equal が例に挙がっている。
もう 1 つは、string[] を object[] として渡したような共変の配列で span のオーバーロードが選ばれ、実行時に ArrayTypeMismatchException が出ることである。

検証環境Git 2.43.0 / .NET SDK(旧) 8.0.428 / .NET SDK(新) 10.0.404 / 2026-11-13 検証(ほか 2 件)
検証日
実行環境
mcr.microsoft.com/dotnet/sdk:10.0 Ubuntu 24.04.5 LTS
バージョン
  • Git 2.43.0
  • .NET SDK(旧) 8.0.428
  • .NET SDK(新) 10.0.404
  • .NET ランタイム(旧) 8.0.34
  • .NET ランタイム(新) 10.0.15

この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。