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.
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";