C# switch expressions, in one minute.

The problem
A ladder to pick one value.
int damage;if ( weapon == Weapon.Sword ) damage = 10;else if ( weapon == Weapon.Bow ) damage = 6;else if ( weapon == Weapon.Fists ) damage = 2;else damage = 1;
Nine lines to pick one number, and damage is repeated on every branch.
The fix
Match a value, return a value.
A switch expression takes a value, matches it against cases, and returns the result of the first match.
weaponswitch{ case => value }
The fix in code
One expression.
int damage = weapon switch{ Weapon.Sword => 10, Weapon.Bow => 6, Weapon.Fists => 2, _ => 1,};
Each line is a case and its result. The underscore catches everything else.
Going further
Match ranges too.
string label = health switch{ <= 0 => "Dead", < 25 => "Critical", < 100 => "Hurt", _ => "Healthy",};
Cases can compare, not just match exactly. Checked top to bottom, first match wins.
The rule
Picking a value? Use a switch expression.
- Exact match
- Weapon.Bow => 6
- Ranges
- < 25 => "Critical"
- Everything else
- _ => 1