Why can't I do ??= in C#?

When I think about it,

foo = foo ?? x 

is really just

foo = foo != null ? foo : x

and at that point, the analogy to += starts to fall apart.


There's no reason why there couldn't be such an operator, but I suspect the added complexity of the language, though slight, outweights the benefit (which I would deem "very slight").

Basically any addition to the language has a pretty high bar to clear. You say you use this quite often - how often, really? While I deem ?? handy, I can't say I use even that terribly frequently.


In general, the C# language design team is conservative about adding new syntax. They say that the value of an addition to the language must be weighed against the cost of increased complexity in the language.

Peter Hallam was the C# Compiler development lead for a while, and also a member of the C# language design team. He wrote about his way of measuring a new feature, called the Yardstick, although he was focused more on interactive GUI features than language features.

This text is particularly relevant to the question of ??=:

Often the right design decision is to not change anything. This is probably the most important lesson I've learned from watching Anders in the C# language design meetings. Often an area of the language is raised in which there apppears to be some real gains which could be made. We could prevent the user from a common coding error, or we could improve the usabilityof the language for a certain problem domain. Then after thinking really hard, through all of the options for addressing the issue, the answer is to do .... nothing! Even though the problem is valid, and it looks like we should be able to add something to improve the situation, after careful reflection there is no way to address the issue which does not cost more than the solution gains. Many of the most important and valuable decisions I've seen Anders make are decisions to not add complexity to the language unless the added value justifies the complexity. In borderline cases, he allmost allways choses nothing over adding something which is marginal.

References:

  • The Yardstick
  • What Do Programmers Really Do Anyway?