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_access
expressionE
is of the formP?.A
. LetT
be the type of the expressionP.A
. The meaning ofE
is determined as follows:
[...]
If
T
is a non-nullable value type, then the type ofE
isT?
, and the meaning ofE
is the same as the meaning of:((object)P == null) ? (T?)null : P.A
Except that
P
is evaluated only once.Otherwise the type of
E
isT
, and the meaning ofE
is the same as the meaning of:((object)P == null) ? null : P.A
Except 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.