I have such code:
if (a() && b != null) { b.doSomething(); }
I need side effect of a()
even if b
is null
. Is it guaranteed by C#? Or C# may omit a()
call if b
is null
?
The IF function is one of the most popular functions in Excel, and it allows you to make logical comparisons between a value and what you expect. So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.
The IF-THEN function in Excel is a powerful way to add decision making to your spreadsheets. It tests a condition to see if it's true or false and then carries out a specific set of instructions based on the results. For example, by inputting an IF-THEN in Excel, you can test if a specific cell is greater than 900.
IF is one of the Logical functions in Microsoft Excel, and there are 3 parts (arguments) to the IF function syntax: logical_test: TEST something, such as the value in a cell. value_if_true: Specify what should happen if the test result is TRUE. value_if_false: Specify what should happen if the test result is FALSE.
Yes, a()
will always be evaluated.
Since the condition is evaluated from left to right, a()
will always be evaluated, but b != null
will only be evaluated if a()
returns true
.
Here's an exact specification reference for you, from the C# Language Specification version 3.0. My emphases and elisions.
7.11.1 Boolean conditional logical operators
When the operands of
&&
or||
are of typebool
[...] the operation is processed as follows:
- The operation
x && y
is evaluated asx ? y : false
. In other words,x
is first evaluated and converted to type bool. Then, ifx
is true, y is evaluated and converted to type bool, and this becomes the result of the operation. Otherwise, the result of the operation is false.
Yes, expressions are evaluated from left to right; so a()
will always be called.
See the C# language spec (ECMA 334, paragraph 8.5):
Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, x + y + z is evaluated as (x + y) + z.
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