When the null conditional operator short-circuits, does it still evaluate method arguments?
Asked Answered
G

2

7

The null conditional operator can be used to skip method calls on a null target. Would the method arguments be evaluated or not in that case?

For example:

myObject?.DoSomething(GetFromNetwork());

Is GetFromNetwork called when myObject is null?

Garrow answered 5/8, 2017 at 12:15 Comment(0)
G
10

They will not be evaluated.

class C
{
    public void Method(int x)
    {
        Console.WriteLine("Method");
    }
}

static int GetSomeValue()
{
    Console.WriteLine("GetSomeValue");
    return 0;
}

C c = null;
c?.Method(GetSomeValue());

This does not print anything. Resharper marks the evaluation of GetSomeValue()as dead code:

enter image description here

Garrow answered 5/8, 2017 at 12:15 Comment(0)
L
0
myObject?.Method();

is basically equivalent to

var temp = myObject;
if (temp != null) {
    temp.Method();
}

You see that no argument can be evaluated if myObject is null.

Note that if you replaced myObject by

Leanaleanard answered 5/8, 2017 at 12:21 Comment(3)
They are not equivalent. Specifically, the former evaluates object only once, the latter twice if non-null. Since they're not equivalent, no conclusions should be drawn from it.Norikonorina
@hvd They are. It is stated as this even in the specs (literally!). And since it is a variable, there is no double evaluation. github.com/ljw1004/csharpspec/blob/gh-pages/…Leanaleanard
They are not in general, as stated in the very specs you link to: "except that P is evaluated only once.", later "except that P is evaluated only once.", yet later "except that P is evaluated only once.", finally "Except that a.b and a.b[0] are evaluated only once." and "except that a.b and a.b[0] are evaluated only once." Yes, for a local variable, double evaluation does not change the results. The part that this is the only exception would be a good addition to your answer, IMO.Norikonorina

© 2022 - 2024 — McMap. All rights reserved.