C# 陳述式多源自 C/C++,並有獨特增修。以下為完整分類:
// 區塊陳述式
static void Main() { F(); G(); { H(); I(); } }
// 標籤與 goto
static void Main(string[] args) {
if (args.Length == 0) goto done;
Console.WriteLine(args.Length);
done:
Console.WriteLine("Done");
}
// 常數
const float pi = 3.14f;
const int r = 123;
// 區域變數
int a;
int b = 2, c = 3;
a = 1;
// if-else
if (args.Length == 0) Console.WriteLine("無參數");
else Console.WriteLine("有參數");
// switch
switch (args.Length) {
case 0: Console.WriteLine("無"); break;
case 1: Console.WriteLine("一個"); break;
default: Console.WriteLine("{0} 個", args.Length); break;
}
// while
while (i < args.Length) { Console.WriteLine(args[i]); i++; }
// do-while
do { s = Console.ReadLine(); } while (s != "Exit");
// for
for (int i = 0; i < args.Length; i++) Console.WriteLine(args[i]);
// foreach
foreach (string s in args) Console.WriteLine(s);
// break 跳出迴圈
while (true) { if (i == args.Length) break; Console.WriteLine(args[i++]); }
// continue 跳過本次迴圈
while (true) { Console.WriteLine(args[i++]); if (i < args.Length) continue; break; }
// return
static int F(int a, int b) => a + b;
// try-catch-throw
try { Console.WriteLine(F(5, 0)); }
catch (Exception e) { Console.WriteLine("錯誤"); }
// checked/unchecked 溢位控制
int x = Int32.MaxValue;
checked { Console.WriteLine(x + 1); } // 拋出例外
unchecked { Console.WriteLine(x + 1); } // 靜默溢位
// lock 執行緒同步
lock (a) { a.P = a.P + 1; }
// using 自動釋放資源
using (Resource r = new Resource()) { r.F(); }
關鍵差異: C# 要求 if 條件必須為布林運算式,不可像 C/C++ 使用整數隱性轉換,避免 if (x = 5) 這類賦值誤寫成比較的常見錯誤。