switch expression

A switch construct that produces a value, with one arm per case and no fall-through between them.

In more detail

Because it evaluates to a value, each arm must produce one, and compilers can check that every possible case is covered. It can be returned or assigned directly.

Examples

qty switch { 0 => "none", 1 => "one", _ => "many" }
C#: value switch { pattern => result }; a missing case raises warning CS8509.
Java: return switch (light) { case RED -> "stop"; case GREEN -> "go"; };
return switch (light) { case RED -> "stop"; case GREEN -> "go"; };

Related terms

Taught in

References

Certification courses