Tutorial :A null coalescing assignment operator? [closed]



Question:

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.


Solution:1

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?


Solution:2

Other programming languages like Ruby use this quite frequently:

something ||= Something.new  


Solution:3

If 'something' is a private field for a property accessor, you can do the following....this would perform the assignment if the field is found to be null.

private Something something;  public Something Something  {      get      {          return something ?? (something = new Something());      }  }  


Solution:4

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....


Solution:5

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.


Solution:6

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


Solution:7

I actually implemented that for PHP7. It's now at RFC proposal stage. https://github.com/php/php-src/pull/1795

Actually it was a question about null coalescing operator in PHP7. Check this:

$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? ‘value’;  I want to check if some var is null and if the same var is null set the same var to ‘value’.  

Hence I am repeating the same variable after the equal operator, this does not feels right.

So I feel that we need another operator like “??=“ similar to +=;

$this->request->data['comments']['user_id’] ??= ‘value’. So if the var is null it’s set to ‘value’ and else stays the same.

In that pull request I tried to implement this.

$ sapi/cli/php -r '$num = null;$num ??= 5; echo $num;'  5  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »