Are function arguments always evaluated in a C# null-conditional function call?
i.e. in the following code:
obj?.foo(bar());
Is bar evaluated if obj is null?
CodePudding user response:
The spec specifies that
A
null_conditional_member_accessexpressionEis of the formP?.A. LetTbe the type of the expressionP.A. The meaning ofEis determined as follows:
[...]
If
Tis a non-nullable value type, then the type ofEisT?, and the meaning ofEis the same as the meaning of:((object)P == null) ? (T?)null : P.AExcept that
Pis evaluated only once.Otherwise the type of
EisT, and the meaning ofEis the same as the meaning of:((object)P == null) ? null : P.AExcept that P is evaluated only once.
In your case, P is obj. A is foo(bar()). If we expand both cases:
((object)obj == null) ? (T?)null : obj.foo(bar())
((object)obj == null) ? null : obj.foo(bar())
By the semantics of the ternary operator, when obj is null, the third operand, obj.foo(bar()) will not be evaluated.
CodePudding user response:
No.
There is no reason to evaluate bar() if obj is null.
Create the example, in dotnetfiddle or elswhere, and make bar output something. Nothing will be outputed.
CodePudding user response:
Running test code indicates that in the Microsoft compiler at least the arguments are not evaluated, however the C# specification doesn't seem to specify this as required behaviour.
