はじめに
この記事では C# 8.0 から使える「switch 式」の書き方を簡単にメモしておきます。
switch 式の書き方
通常の switch 文は以下のように書きます。
private string GetStatusText()
{
int randomNum = Random.Range(0,3);
//通常の switch 文
switch (randomNum)
{
case 0: return "攻撃";
case 1: return "守備";
case 2: return "待機";
default: return string.Empty;
}
}
これを switch 式で書くと以下のようになります。
「switch 式」という名前の通り、1つの式として簡易的に記述できるのでいいですね。
private string GetStatusText()
{
int randomNum = Random.Range(0,3);
// switch 式
return randomNum switch
{
0 => "攻撃" ,
1 => "守備",
2 => "待機",
_ => string.Empty,
};
}