Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Variable to a Switch's Result

In C#, is there a way to set a variable from a switch expression? For example:

var a = switch(b)
{
    case c:
    d;

    case e:
    f;

    default:
    g;
};

Is it possible in any other language?

like image 464
vbullinger Avatar asked Nov 16 '11 17:11

vbullinger


3 Answers

From C# 8 onwards:

Yes, switch expressions were introduced in C# 8. In terms of syntax, the example would be:

var a = b switch
{
    c => d,
    e => f,
    _ => g
};

... where c and e would have to be valid patterns to match against b. _ represents the default case.

Before C# 8:

No, switch is a statement rather than an expression which can be evaluated.

Of course, you can extract it into another method:

int x = DoSwitch(y);

...

private int DoSwitch(int y)
{
    switch (y)
    {
        case 0: return 10;
        case 1: return 20;
        default: return 5;
    }
}

Alternatively, you could use a Dictionary if it's just a case of simple, constant mappings. If you can give us more information about what you're trying to achieve, we can probably help you work out the most idiomatic way of getting there.

like image 84
Jon Skeet Avatar answered Nov 08 '22 11:11

Jon Skeet


No, you can't use a switch statement as an expression. Another way to write it is nested conditional operators:

var a = b == c ? d:
        b == e ? f:
                 g;
like image 16
Mark Byers Avatar answered Nov 08 '22 12:11

Mark Byers


This is not possible in C#.

The closest would be to either move this into a method, or do the assignment in each case individual, ie:

int a;
switch(b)
{
 case c:
     a = d; break;
 case e:
     a = f; break;
 default:
     a = g; break;
};

Is it possible in any other language?

Yes. For example, most functional languages support something similar. For example, F#'s pattern matching provides a (much more powerful) version of this.

like image 6
Reed Copsey Avatar answered Nov 08 '22 11:11

Reed Copsey