How can I combine return and switch case statements in C#?
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.
Note: As of C#8 (ten years later!) this is now possible, please see the answer below.
switchandreturncan’t combine that way, becauseswitchis 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: