上級 › SwitchExpressionException の原因と直し方 › パターン3
SwitchExpressionException の原因と直し方
switch式が全てのパターンを網羅していないとき、コンパイラは警告を出しますが止めません。
1 class Program { 2 static string Label(int code) { 3 return code switch { 4 200 => "OK", 5 404 => "Not Found", 6 }; 7 } 8 static void Main(string[] args) { 9 System.Console.WriteLine(Label(___)); ^ 10 } 11 }
Unhandled exception. System.Runtime.CompilerServices.SwitchExpressionException: Non-exhaustive switch expression failed to match its input.
at Program.Label(Int32 code) in Program.cs:line 3
空欄を埋めてビルドを通す
HTTPステータスコードのように種類が多い値をswitch式で扱うときほど、既定パターンの用意が重要になります。
次の問題