views:

580

answers:

5

It would be really nice if C# allowed an ??= operator. I've found myself writing the following frequently:

something = something ?? new Something();

I'd rather write it like this:

something ??= new Something();

Thoughts? New language extensions are always controversial by their nature.

+3  A: 

I'm honestly torn on the =++ operator in the first place, and it's usage is rather widespread and common. From a clarity point of view, the extra couple of characters you need type probably isn't worth the change to the language to add a ??=. If this was a vote, I'd vote against that change to the language (good question, bad idea. :-)

I haven't tried this, but could you map ??= to a macro in visual studio that just did the rewrite for you?

WaldenL
+2  A: 

I would say that the '??' operator and more pertinently the above pattern is not so common and so a new operator is overkill.

Mohit Chakraborty
My thoughts exactly.
marc_s
+1  A: 

I'm not necessarily against the operator, however, that kind of variable reuse just doesn't feel like the "right way" to me. Bugs that should have been obvious NULL pointers end up populated with unexpected data and work in some unexpected way, etc....

overslacked
+1  A: 

As ?? is shorthand for using the ternary operator in a fashion similar to:

(myObject != null) ? myObject : somethingElse;

rather than shorthand for an arithmetic operation, I don't think a ??= operation is a good fit. It's a conditional operator.

Jeff Yates
+4  A: 

Other programming languages like Ruby use this quite frequently:

something ||= Something.new
Bob Aman