Curious null-coalescing operator custom implicit conversion behaviour

前端 未结 5 1335
粉色の甜心
粉色の甜心 2020-11-30 16:32

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

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 16:55

    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:

    1. A ?? B expands to A.HasValue ? A : B
    2. A is our x ?? y. Expand to x.HasValue : x ? y
    3. replace all occurrences of A -> (x.HasValue : x ? y).HasValue ? (x.HasValue : x ? y) : B

    Here 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 ?? is implemented, rather than a compiler bug. Take-Away: Don't create implicit casting operators with side effects.

    It seems to be a compiler bug revolving around how ?? is implemented. Take-away: don't nest coalescing expressions with side-effects.

提交回复
热议问题