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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
From C# 8 onwards:
Yes, switch expressions were introduced in C# 8. In terms of syntax, the example would be:
… where
candewould have to be valid patterns to match againstb._represents the default case.Before C# 8:
No,
switchis a statement rather than an expression which can be evaluated.Of course, you can extract it into another method:
Alternatively, you could use a
Dictionaryif 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.