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

时间:2017-08-05 12:15:38

标签: c# c#-6.0 null-conditional-operator

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?

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分: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