How can I combine return
and switch case
statements?
I want something like
return switch(a) { case 1:"lalala" case 2:"blalbla" case 3:"lolollo" default:"default" };
I know about this solution
switch(a) { case 1: return "lalala"; case 2: return "blalbla"; case 3: return "lolollo"; default: return "default"; }
But I want to only use the return
operator.
The JavaScript switch statement can contain return statements if it is present inside a function. The function will return the value in the switch statement and the code after the switch statement will not be executed.
Yes, you can use return instead of break ... break is optional and is used to prevent "falling" through all the other case statements. So return can be used in a similar fashion, as return ends the function execution.
The simple answer is No. You cant use it like that. Switch works with single expression.
You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.
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 from the switch statement.
- The case and : elements are replaced with =>. It's more concise and intuitive.
- The default case is replaced with a _ discard.
- The bodies are expressions, not statements.
For more information and examples check the Microsoft's C# 8 Whats New.
Note: As of C#8 (ten years later!) this is now possible, please see the answer below.
switch
and return
can't combine that way, because switch
is a statement, not an expression (i.e., it doesn't return a value).
If you really want to use just a single return
, you could make a Dictionary to map the switch variable to return values:
var map = new Dictionary<int, string>() { {1, "lala"}, {2, "lolo"}, {3, "haha"}, }; string output; return map.TryGetValue(a, out output) ? output : "default";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With