Does C# ?? operator get called twice?

Does the method on the left side of the ?? operator in C# get called twice? Once for the evaluation and once for the assignment?

In the following line:

int i = GetNullableInt() ?? default(int);

I would assume that the GetNullableInt() method would need to be called first, so the result could be evaluated, before making the assignment. If this does NOT happen then the variable "i" would need to be assigned and then evaluated which seems dangerous for the item receiving the assignment in that, during an object assignment, it could theoretically be prematurely assigned a null value during the first stage only to have it replaced by the result of the method on the right.

?? Operator (C# Reference)

Jon Skeet
people
quotationmark

There is a bug in the current C# compiler which will cause some aspects of evaluating the first operand to occur twice, in very specific situatoins - but no, GetNullableInt() will only be called once. (And the bug has been fixed in Roslyn.)

This is documented in the C# 5 specification in section 7.13, where each of the bullets in the list of options (based on what conversions are required) includes "At run-time, a is first evaluated." (a is the expression in the first operand.) It is only stated once, so it's only evaluated once. Note that the second operand is only called if it needs to be (i.e. if the first operand is null.)

Importantly, even if the type of i were int?, the assignment to i only happens after the expression to the right of the assignment operator is fully evaluated. It doesn't assign one value and then potentially assign a different one - it works out which value is going to be assigned, and then assigns it. This is how assignment always works. That becomes very important when there are conditional operators. For example:

Person foo = new Person();
foo = new Person { Spouse = foo };

That completely construts the new Person (assigning the old value of foo to its Spouse property) before assigning the reference to foo.

people

See more on this question at Stackoverflow