分支語句讓程式根據條件執行不同路徑。C# 提供 if-else 與 switch-case 兩大機制。
if (條件)
{
// 條件為 true 時執行
}
else
{
// 條件為 false 時執行
}
double x = Convert.ToDouble(Console.ReadLine());
if (x > 1000)
Console.WriteLine("x 很大");
else if (x > 100)
Console.WriteLine("x > 100");
else if (x > 0)
Console.WriteLine("x 在 0 到 100 之間");
else
Console.WriteLine("x <= 0");

if (x > 1000)
{
if (x == 9000) Console.WriteLine("x = 9000");
if (x == 8000) Console.WriteLine("x = 8000");
if (x > 5000) Console.WriteLine("x > 5000");
Console.WriteLine("x 很大");
}
編譯器逐條判斷,僅執行符合條件的區塊。層級過深會降低可讀性,建議改用 switch 或多型設計。
適用於單一變數對多個常數值的比對,結構清晰、效率較高(編譯器優化為跳躍表)。
switch (運算式)
{
case 常數1:
陳述句1;
break;
case 常數2:
陳述句2;
break;
default:
預設處理;
break;
}
int day = Convert.ToInt32(Console.ReadLine());
switch (day)
{
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;
default: Console.WriteLine("其他"); break;
}
string input = Console.ReadLine();
switch (input)
{
case "hi":
case "hello": // 多 case 共用邏輯(無 break 會貫穿)
Console.WriteLine("打招呼");
break;
default:
Console.WriteLine("未識別");
break;
}

每個 case 結尾需加 break,否則會「貫穿」執行下一個 case。C# 不允許隱式貫穿(需明確 goto case),但同一 case 可堆疊多個標籤共用邏輯。
switch 運算式必須為整數型別、char、string 或 enum,不支援 float/double。