Are function parameters evaluated in a C# null-conditional function call?

Viewed 31

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?

3 Answers

The spec specifies that

A null_conditional_member_access expression E is of the form P?.A. Let T be the type of the expression P.A. The meaning of E is determined as follows:

  • [...]

  • If T is a non-nullable value type, then the type of E is T?, and the meaning of E 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 is T, and the meaning of E 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.

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.

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.

Related