Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine return and switch

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.

like image 640
Neir0 Avatar asked Jul 26 '10 10:07

Neir0


People also ask

Can you use return in switch statement?

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.

Can we use return instead of break in switch?

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.

Can I use && in switch?

The simple answer is No. You cant use it like that. Switch works with single expression.

Why do switches need breaks?

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.


2 Answers

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.

like image 77
Daniel Z. Avatar answered Oct 01 '22 21:10

Daniel Z.


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"; 
like image 29
tzaman Avatar answered Oct 01 '22 22:10

tzaman