Combine switch expression with let keyword #4154
-
It would be cool if it was possible to assign a new variable before the switch case expression is evaluated. var result = value switch {
string let var s = value.ToString() => s[..s.IndexOf('x')],
_ => null
} This is just a very simple example. Of course the let expression and case expressions can be more complex. Whats your oppinion on this? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
You can currently do: var result = value switch {
string s => s[..s.IndexOf('x')],
_ => null
} |
Beta Was this translation helpful? Give feedback.
-
The best way to do this right now would be to call a method string ConvertStr(string s) => s[..s.IndexOf('x')];
var result = type switch {
Enum.TypeString => ConvertStr(value.ToString()),
_ => null
} So this is achievable right now. But I still want to leave the discussion open |
Beta Was this translation helpful? Give feedback.
-
This is brilliant. |
Beta Was this translation helpful? Give feedback.
-
With #3037 you would be able to do: var result = type switch {
Enum.TypeString value => {
var s = value.ToString();
s[..s.IndexOf('x')]
},
_ => null
} |
Beta Was this translation helpful? Give feedback.
The best way to do this right now would be to call a method
So this is achievable right now. But I still want to leave the discussion open