C
C#2d ago
Faker

✅ Can someone explain how this ternary expression works

c#
total -= TotalMeetsMinimum() ? 5.00 : 0.00;
c#
total -= TotalMeetsMinimum() ? 5.00 : 0.00;
Given that TotalMeetsMinimum returns a boolean. I don't understand because of the -= symbol, like here, it's like we are doing total = total - TotalMeetsMinimum() ? 5.00 : 0.00; ? If no, then how do we read that expression please
24 Replies
Angius
Angius2d ago
Yes, that's what it is x -= y is the same as x = x - y Same goes for other compound operators, like +=, *=, /=, etc
Faker
FakerOP2d ago
yep but the body of the ternary operator should be a boolean, here we are doing total - TotalMeetsMinium() or is there some operator precedence something like ?
Angius
Angius2d ago
No, we're doing -=
Mąż Zuzanny Harmider Szczęście
how does -= return bool
Faker
FakerOP2d ago
no I mean TotalMeetsMinimum() returns a bool
Mąż Zuzanny Harmider Szczęście
still oh, so it removes 0 or 1?
Angius
Angius2d ago
?
Angius
Angius2d ago
To answer your question, the compiler wraps the ternary in parentheses So, yeah, there's a sort of precedence in this case
Faker
FakerOP2d ago
yep it's like we execute the ternary first, then total - whateverOutcomes
Mąż Zuzanny Harmider Szczęście
oh nvm, i understand now: u could write it like this:
if(TotalMeetsMinimum()){
total-=5
}else{
total-=0
}
if(TotalMeetsMinimum()){
total-=5
}else{
total-=0
}
Faker
FakerOP2d ago
yeah I was just confuse of what was happening behind the scenes but it's clear now
Angius
Angius2d ago
You can always use Sharplab to see what the compiler lowers the code to Even JIT Asm and IL if you want
Faker
FakerOP2d ago
wait, will just try sharplab
Faker
FakerOP2d ago
I just paste my code in the public void M() ?
No description
Angius
Angius2d ago
Or just paste it straight Sharplab supports TLS
Faker
FakerOP2d ago
ok 2sec yep, then on the right hand side, what does it show pls
Angius
Angius2d ago
It shows what the compiler lowers your code into Or, in other words, what the code becomes after removing all the syntax sugar
Faker
FakerOP2d ago
yep, but this is not IL, right ?
Angius
Angius2d ago
No You can switch to IL if you want
Angius
Angius2d ago
No description
Faker
FakerOP2d ago
ahhh yeah interesting
Faker
FakerOP2d ago
Yeah I see, I should learn how to interpret this, can be used to better understand things
No description
Faker
FakerOP2d ago
Thanks !

Did you find this page helpful?