Basics
C# Switch
Switch Expressions
C# switch expressions handle cases with type patterns.
Introduction to C# Switch
The switch statement in C# is a control structure that allows you to choose between multiple options based on the value of an expression. Unlike the if-else statement, which evaluates conditions sequentially, the switch statement provides a cleaner and more efficient way to handle multiple potential values of a variable.
Basic Switch Statement Example
Here's a simple example of a switch statement that evaluates an integer value:
C# Switch Expressions
With C# 8.0 and later, you can use switch expressions, which provide a more concise syntax compared to traditional switch statements. This is particularly useful when you want to evaluate expressions and return values directly.
Switch with Type Patterns
Switch expressions can also handle type patterns, allowing you to match types at runtime and execute code accordingly. This feature is particularly powerful for processing different object types.
When Clauses in Switch Expressions
Switch expressions support when clauses, which add additional condition checks to each case. This can be useful for more complex logic.