Multiple statements in a switch expression: C# 8 [duplicate]

Your only supported choice is the func like you did. See [this article][1] for more information. His example: var result = operation switch { “+” => ((Func<int>)(() => { Log(“addition”); return a + b; }))(), “-” => ((Func<int>)(() => { Log(“subtraction”); return a – b; }))(), “/” => ((Func<int>)(() => { Log(“division”); return a / … Read more

What are switch expressions and how are they different from switch statements?

The switch statement: Unlike the if/else if/else statement, a switch statement can have a number of possible execution paths. A switch works with the primitive types, byte, short, char, and int, their respective wrapper types (Byte, Short, Character, and Integer), enumerated types, and the String type1. While an if-else statement is used to test expressions … Read more

Combine return and switch in C#

Actually this is possible using switch expression starting with C# 8. return a switch { 1 => “lalala”, 2 => “blalbla”, 3 => “lolollo”, _ => “default” }; Switch Expression There are several syntax improvements here: The variable comes before the switch keyword. The different order makes it visually easy to distinguish the switch expression … Read more

Switch expression with void return type

Maybe yield a Consumer of Event, so you yield something useful, the trade off is one more line for consumer.accept. Consumer<Event> consumer = switch (event.getEventType()) { case ORDER -> e -> handle((OrderEvent) e); case INVOICE -> e -> handle((InvoiceEvent) e); case PAYMENT -> e -> handle((PaymentEvent) e); }; consumer.accept(event); Continue if you concern performance Based … Read more

Multi-variable switch statement in C#

Yes. It’s supported as of .NET 4.7 and C# 8. The syntax is nearly what you mentioned, but with some parenthesis (see tuple patterns). switch ((intVal1, strVal2, boolVal3)) { case (1, “hello”, false): break; case (2, “world”, false): break; case (2, “hello”, false): break; } If you want to switch and return a value there’s … Read more

Combine return and switch

Actually this is possible using switch expressions starting with C# 8. return a switch { 1 => “lalala”, 2 => “blalbla”, 3 => “lolollo”, _ => “default” }; Switch Expressions There are several syntax improvements here: The variable comes before the switch keyword. The different order makes it visually easy to distinguish the switch expression … Read more