Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 294
boot4life Avatar asked Jan 29 '23 20:01

boot4life


1 Answers

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

like image 129
boot4life Avatar answered Feb 02 '23 09:02

boot4life