Thursday, October 24, 2024

C# Different types of Switch expressions and Switch Statement


In C#, switch expressions were introduced in C# 8.0 as a more concise and expressive way to write switch statements. There are two main types of switch expressions in C#:

1. Simple Switch Expression:

A simple switch expression is used when you have a single expression to return based on the value of the input. It has the following syntax:

 result = switch (input)
   {
       case value1: expression1;
       case value2: expression2;
       // ...
       default: expressionN;
   };
Here, the value of input is compared to each case label, and the corresponding expression is returned when a match is found. If no match is found, the default expression is returned.

Example:

 string result = input switch
   {
       "apple" => "It's a fruit",
       "carrot" => "It's a vegetable",
       _ => "Unknown"
   };

2. Property Pattern Switch Expression:

Property pattern switch expressions allow you to match against properties of objects in the cases. It is useful when you want to switch based on the properties of an object rather than just its value. It has the following syntax:

 result = input switch
   {
       { Property1: Value1 } => expression1,
       { Property2: Value2 } => expression2,
       // ...
       _ => expressionN
   };
   
Example:

var person = new Person { Name = "John", Age = 30 };
   string result = person switch
   {
       { Age: 18 } => "You are legally an adult",
       { Age: var age } => $"You are {age} years old",
       _ => "Unknown"
   };
   
In both types of switch expressions, the _ is used as a discard symbol to indicate a catch-all case. It matches any value that doesn't match any of the preceding cases.

Switch expressions are more concise and readable than traditional switch statements, especially when you need to assign a value based on a specific condition. They also support additional features like pattern matching, making them powerful tools for controlling program flow based on complex conditions.

Now we look at differences between Switch expression and  Switch Statement.

Difference between Switch statement and Switch expressions in C#

In C#, a switch statement and a switch expression are both used for branching based on the value of a variable, but they have differences in syntax, behavior, and usage. Let's differentiate between the two:

1. Syntax:

Switch Statement:

     switch (variable)
     {
         case value1:
             // code block
             break;
         case value2:
             // code block
             break;
         // more cases
         default:
             // code block for default case
             break;
     }
     
Switch Expression:

     var result = variable switch
     {
         value1 => expression1,
         value2 => expression2,
         // more cases
         _ => defaultExpression // default case
     };

2. Use of case vs. Pattern Matching: 

  • In a switch statement, you use case followed by a constant value or an expression to match against the variable. 
  • In a switch expression, you can use patterns (including constant patterns, type patterns, and more) to match against the variable.

3. Return Value:

  • Switch Statement: The switch statement uses the break keyword to exit the switch block after executing the corresponding case. It's primarily used for control flow and doesn't return a value.
  • Switch Expression: The switch expression directly returns a value based on the matched case. There's no need for break statements, and it's used for expressions that produce a result.

4. Default Handling:

  • Switch Statement: The default case is specified using the default keyword and is executed if no other cases match.
  • Switch Expression: The default case is handled using the _ pattern and specifies the default expression to be executed if no other cases match.

5. Expression vs. Statement:

  • A switch statement is a statement and is used for control flow.
  • A switch expression is an expression and can be used to assign a value to a variable or as part of a larger expression.
Here's a simple example to illustrate the difference:
// Switch statement
int number = 2;
string resultStatement;

switch (number)
{
    case 1:
        resultStatement = "One";
        break;
    case 2:
        resultStatement = "Two";
        break;
    default:
        resultStatement = "Unknown";
        break;
}

// Switch expression
string resultExpression = number switch
{
    1 => "One",
    2 => "Two",
    _ => "Unknown"
};
In summary, switch statements are used for control flow and can execute multiple statements for a case, while switch expressions are used for producing a result and use patterns for matching and returning an expression.

No comments:

Post a Comment

Hot Topics