Share via


switch (C# リファレンス)

switch ステートメントは、候補のリストから実行する switch セクションを選択するための制御ステートメントです。

switch ステートメントには、1 つ以上の switch セクションが含まれています。 各 switch セクションには、1 つ以上の case ラベルと、そのあとに続く 1 つ以上のステートメントのリストが含まれています。 次の例に、3 つの switch セクションを持つ簡単な switch ステートメントを示します。 各 switch セクションには、case 1 のような case ラベルと、2 つのステートメントが含まれます。

int caseSwitch = 1;
switch (caseSwitch)
{
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 2:
        Console.WriteLine("Case 2");
        break;
    default:
        Console.WriteLine("Default case");
        break;
}

解説

各 case ラベルでは、定数値を指定します。 switch ステートメントは、switch 式の値に一致する case ラベルを持つ switch セクション (この例では caseSwitch) に制御を移動します。 一致する値が case ラベルにない場合、制御は default セクションに移動します (default セクションがある場合)。 default セクションがない場合は、何の処理も行われないまま、制御は switch ステートメントの外部に移動します。 前の例では、case 1 が caseSwitch の値に一致するため、ステートメント内の最初の switch セクションが実行されます。

switch ステートメントには、任意の数の switch セクションを含めることができ、また (文字型の case ラベルも使用している以下の例に示すように) 各セクションに 1 つ以上の case ラベルを含めることができます。 ただし、複数の case ラベルで同じ定数値を使用することはできません。

選択された switch セクションにおけるステートメント リストの実行は、ステートメント リストに沿って最初のステートメントから順に開始され、通常は、break、goto case、return、throw などのジャンプ ステートメントに達するまで続きます。 この時点で、制御は switch ステートメントの外側、または他の case ラベルに移動します。

C++ とは異なり、C# では 1 つの switch セクションから次のセクションへ実行が連続することが許可されません。 次のコードでは、エラーが発生します。

switch (caseSwitch)
{
    // The following switch section causes an error.
    case 1:
        Console.WriteLine("Case 1...");
        // Add a break or other jump statement here.
    case 2:
        Console.WriteLine("... and/or Case 2");
        break;
}

最終セクションも含め、各 switch セクションの末尾には到達不可能であることが C# の要件です。つまり、他のいくつかの言語とは異なり、コードが次の switch セクションにフォール スルーすることはできません。通常この要件は、break ステートメントを使用することによって満たされますが、ステートメント リストの末尾に到達不可能であるため、次のコードも有効になります。

case 4:
    while (true)
        Console.WriteLine("Endless looping. . . .");

使用例

次の例は、switch ステートメントの要件と機能について示しています。

class Program
{
    static void Main(string[] args)
    {
        int switchExpression = 3;
        switch (switchExpression)
        {
            // A switch section can have more than one case label. 
            case 0:
            case 1:
                Console.WriteLine("Case 0 or 1");
                // Most switch sections contain a jump statement, such as 
                // a break, goto, or return. The end of the statement list 
                // must be unreachable. 
                break;
            case 2:
                Console.WriteLine("Case 2");
                break;
                // The following line causes a warning.
                Console.WriteLine("Unreachable code");
            // 7 - 4 in the following line evaluates to 3. 
            case 7 - 4:
                Console.WriteLine("Case 3");
                break;
            // If the value of switchExpression is not 0, 1, 2, or 3, the 
            // default case is executed. 
            default:
                Console.WriteLine("Default case (optional)");
                // You cannot "fall through" any switch section, including
                // the last one. 
                break;
        }
    }
}

最後の例では、文字列変数 strと文字列の case ラベルを使用して、実行の流れを制御します。

class SwitchTest
{
    static void Main()
    {
        Console.WriteLine("Coffee sizes: 1=small 2=medium 3=large");
        Console.Write("Please enter your selection: ");
        string str = Console.ReadLine();
        int cost = 0;

        // Notice the goto statements in cases 2 and 3. The base cost of 25 
        // cents is added to the additional cost for the medium and large sizes. 
        switch (str)
        {
            case "1":
            case "small":
                cost += 25;
                break;
            case "2":
            case "medium":
                cost += 25;
                goto case "1";
            case "3":
            case "large":
                cost += 50;
                goto case "1";
            default:
                Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
                break;
        }
        if (cost != 0)
        {
            Console.WriteLine("Please insert {0} cents.", cost);
        }
        Console.WriteLine("Thank you for your business.");
    }
}
/*
    Sample Input: 2

    Sample Output:
    Coffee sizes: 1=small 2=medium 3=large
    Please enter your selection: 2
    Please insert 50 cents.
    Thank you for your business.
*/

C# 言語仕様

詳細については、「C# 言語仕様」を参照してください。言語仕様は、C# の構文と使用法に関する信頼性のある情報源です。

参照

関連項目

C# のキーワード

switch ステートメント (C++)

if-else (C# リファレンス)

概念

C# プログラミング ガイド

その他の技術情報

C# リファレンス