3 ms·
How would this work if I need to update multiple variables? int value1 = 0; int value2 = 0; if (condition) { value1 = 8; value2 = 16; } else {
by ahci8e 2y ago
How would this work if I need to update multiple variables?
int value1 = 0;
int value2 = 0;
if (condition) {
value1 = 8;
value2 = 16;
} else {
value1 = 128;
value2 = 256;
}
Would I have to repeat the if expression twice?
int value1 = if (condition) { 8 } else { 128 };
int value2 = if (condition) { 16 } else { 256 };
- tomtheelder 2y agoDepends on the language a bit, but a common feature in these languages is the tuple. Using a tuple you would end up with something like: let (value1, value2) = if (condition) { (8, 16) } else { (16, 256) } Or else you’d just use some other sort of compound value like a struct or something. Tuple is just convenient for doing it on the fly.
- runevault 2y agohah we gave basically the same example on the same minute. I love destructuring so much, I don't know if I'd want to use a language without it anymore.
- tomtheelder 2y agoIt’s actually so painful to go back to languages without destructuring and pattern matching.
- runevault 2y agoAs someone who writes a fair bit of c# making switch and if's into expressions and adding Discriminated Unions (which they are actually working on) are my biggest "please give me this." Plus side I dabble in f# which is so much more expressive.
- throwaway9502 2y ago[dead]
- lyu07282 2y agoSame for me in the Scala vs. Java world, it's hard once you get used to how awesome expressions over statements and algebraic data types/case enums/"discriminated unions" are. But I haven't done much C# (yet) myself, could you clarify for me: does C# have discriminated unions? I didn't think the language supported that (only F# has them)?
- runevault 2y agoThe c# team is working on a version of them they are calling Typed Unions, not guaranteed yet but there is an official proposal that I believe is 2 weeks old. https://github.com/dotnet/csharplang/blob/main/proposals/TypeUnions.md https://github.com/dotnet/csharplang/blob/main/proposals/Typ...
- lyu07282 2y agoCool, thanks for answering
- runevault 2y agoDepends on the language. if you have destructuring you can do it all at once. So like I believe you can do this in Rust (haven't written it in a while, I know it has destructuring of tuples) let (a, b) = if (condition) { (1, "hello") } else { (3,"goodbye") }
- another2another 2y ago.. save yourself an else : int value1 = 128; int value2 = 256; if (condition) { value1 = 8; value2 = 16; }