Code Fix

初級switch文のフォールスルー禁止エラーの原因と直し方 › パターン2

switch文のフォールスルー禁止エラーの原因と直し方

C#のswitch文はCやJavaと違い、暗黙のフォールスルーを認めません。

 1  class Program {
 2      static void Main(string[] args) {
 3          string color = "red";
 4          switch (color) {
 5              case "red":
 6                  System.Console.WriteLine("stop");
 7              _________________
                        ^
 8              case "green":
 9                  System.Console.WriteLine("go");
10                  break;
11          }
12      }
13  }
Program.cs(5,13): error CS0163: Control cannot fall through from one case label ('case "red":') to another

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

switch文のフォールスルー禁止エラーの原因と直し方

各caseの終わり方に明示的な文が必要です。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)