Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Visual Studio 2019 recommend a switch expression instead of a switch statement?

Visual Studio 2019 recommended converting a switch statement I had written to a switch expression (both included below for context).

For a simple example such as this, is there any technical or performance advantage to writing it as an expression? Do the two versions compile differently for example?

Statement

switch(reason)
{
    case Reasons.Case1: return "string1";
    case Reasons.Case2: return "string2";
    default: throw new ArgumentException("Invalid argument");
}

Expression

return reason switch {
    Reasons.Case1 => "string1",
    Reasons.Case2 => "string2",
    _ => throw new ArgumentException("Invalid argument")
};
like image 315
AGB Avatar asked Apr 16 '20 09:04

AGB


People also ask

What is expression in switch?

The result of a switch expression is the value of the expression of the first switch expression arm whose pattern matches the input expression and whose case guard, if present, evaluates to true . The switch expression arms are evaluated in text order.

What type must the expression be in a switch statement?

The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

Can switch statements use expressions?

Java SE 12 introduced switch expressions, which (like all expressions) evaluate to a single value, and can be used in statements.

Which is better if else or switch in C#?

if-else better for boolean values: If-else conditional branches are great for variable conditions that result into a boolean, whereas switch statements are great for fixed data values.


1 Answers

In the example you give there's not a lot in it really. However, switch expressions are useful for declaring and initializing variables in one step. For example:

var description = reason switch 
{
    Reasons.Case1 => "string1",
    Reasons.Case2 => "string2",
    _ => throw new ArgumentException("Invalid argument")
};

Here we can declare and initialize description immediately. If we used a switch statement we'd have to say something like this:

string description = null;
switch(reason)
{
    case Reasons.Case1: description = "string1";
                        break;
    case Reasons.Case2: description = "string2";
                        break;
    default:            throw new ArgumentException("Invalid argument");
}

One downside of switch expressions at the moment (in VS2019 at least) is that you can't set a breakpoint on an individual condition, only the whole expression. However, with switch statements you can set a breakpoint on an individual case statement.

like image 76
Sean Avatar answered Nov 15 '22 08:11

Sean