Search code examples
c#expression-evaluationnull-conditional-operator

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


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?


Solution

  • 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.