Note: this appears to have been fixed in Roslyn
This question arose when writing my answer to this one, which talks about the associativity of the n
Actually, I'll call this a bug now, with the clearer example. This still holds, but the double-evaluation is certainly not good.
It seems as though A ?? B is implemented as A.HasValue ? A : B. In this case, there's a lot of casting too (following the regular casting for the ternary ?: operator). But if you ignore all that, then this makes sense based on how it's implemented:
A ?? B expands to A.HasValue ? A : BA is our x ?? y. Expand to x.HasValue : x ? y(x.HasValue : x ? y).HasValue ? (x.HasValue : x ? y) : BHere you can see that x.HasValue is checked twice, and if x ?? y requires casting, x will be cast twice.
I'd put it down simply as an artifact of how Take-Away: Don't create implicit casting operators with side effects. ?? is implemented, rather than a compiler bug.
It seems to be a compiler bug revolving around how ?? is implemented. Take-away: don't nest coalescing expressions with side-effects.