Consider the following two alternatives of getting the higher number between currentPrice
and 100
...
int price = currentPrice > 100 ? currentPrice : 100
int price = Math.Max(currentPrice, 100)
I raised this question because I was thinking about a context where the currentPrice
variable could be edited by other threads.
In the first case... could price
obtain a value lower than 100
?
I'm thinking about the following:
if (currentPrice > 100) {
//currentPrice is edited here.
price = currentPrice;
}
It is not threadsafe.
?:
is just shortcut for normal if
, so your if
sample is equivalent to ?
one - you can get price lower than 100 if there is no locking outside this code.
Not a specialist in C#, but even var++ is not thread save, since may translated to from reading into/writing from register in assembly.
Ternary operator is far more complicated. It has 3 parts, while each part can be endlessly big (e.g. call to some function). Therefore, it's pretty easy to conclude that ternary operator is not thread safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With