开发者

Ternary operator usage

开发者 https://www.devze.com 2023-03-20 06:01 出处:网络
Whats wrong with this seemingly straightforward code? invoice.GST > gstValue ? invoice.GST -= gstVa开发者_如何学Golue : invoice.GST = 0;

Whats wrong with this seemingly straightforward code?

invoice.GST > gstValue ? invoice.GST -= gstVa开发者_如何学Golue : invoice.GST = 0;

VS complains

Only assignment, call, increment, decrement, and new object expressions can be used as a statement


Try this:

invoice.GST = ((invoice.GST>gstValue)?(invoice.GST - gstValue):0);


Because you cannot use invoice.GST > gstValue ? invoice.GST -= gstValue : invoice.GST = 0; as a statement (like VS told you). Same like you cannot do this: int i = 0; i;

You could write it as: invoice.GST = Math.Max(0, invoice.GST - gstValue);


invoice.GST = invoice.GST > gstValue ? invoice.GST - gstValue : 0;

The ternary operator is like -, +, % and other operators.


The expressions mentioned make sense to use as statements, because they cause side effects.

Generally it doesn't make sense to have an operation with no side effects as a statement, because removing the operator and just evaluating the operands would have the same effect, these usually indicate that the behavior is not what the programmer intended.

The exceptions to this are the three operators which conditionally evaluate their operands (the other two are && and ||) -- eliminate the operator and the side effect of the operand changes. In C and C++ you will sometimes find these operators used solely to cause conditional evaluation, but C# does not allow this. In all three cases, the conditional evaluation can be gotten using an if statement, which also makes the code more readable.


Try this:

invoice.GST -= invoice.GST > gstValue ? gstValue : invoice.GST; 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号