Rob P.
Rob P.

Reputation: 15071

Null Conditional Operator Only Evaluates Once

I was reading about the Null Conditional operator introduced in C# 6.0 but I'm not understanding it fully.

From https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6

int? first = customers?[0].Orders.Count();

This example is essentially equivalent to:

int? first = (customers != null) ? customers[0].Orders.Count() : null;

Except that customers is only evaluated once.

Can someone elaborate on the 'evaluated once' verse (I'm assuming) evaluated twice?

Upvotes: 2

Views: 55

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127573

Here is a better equivalency to your first statement

var temp = customers;
int? first;
if(temp != null)
{
    first = temp[0].Orders.Count();
}
else
{
    first = null;
}

The variable customers is only "touched" once. This is more significant when customers is a property that does some action in the get or is a function.

private int accessCount = 0;
private Customers[] _customers;
private Customers[] customers 
{
    get
    {
        accessCount++;
        return _customers;
    }
    set
    {
        _customers = value;
    }
}

In your 2nd example the customers property would have to be "touched" twice, once for the null check once for the indexer, giving accessCount a value of 2.

Upvotes: 1

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

It means the program accesses customers only once. In the second example, customers is accessed twice, first for the null check and second for the Orders property if it's non-null.

In the new feature, customers will be accessed only once, and if it's non-null, it won't be accessed again (e.g. it won't be possible it to become null if something modifies the field) and the already-accessed object will be used.

Upvotes: 1

Related Questions