Can you get the value being switched on inside a switch expression

Viewed 122

Is there a way to do this

int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    _ => someMethod([switch value])
}

to use the value being switched on inside the switch expression? Or do I have to do this

var myString = object.GetString()
int i = myString switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    _ => someMethod(myString)
}

I know it's not that big of a deal to declare myString; I'm just wondering if the syntax exists.

2 Answers

What about this?

int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    { } s => someMethod(s)
}

It will get anything but null.

Of course it is only usable if you want to catch any type there. If you know for sure it will be a string value, and someMethod expects a string value also, you can go like this:

string s => someMethod(s)

Yes, it's easy:

int i = object.GetString() switch
{
    "this" => 1,
    "that" => 2,
    "the other" => 3,
    string value => someMethod(value)
};
Related