Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A null coalescing assignment operator? [closed]

Tags:

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.

like image 251
CodeMonkeyKing Avatar asked Mar 17 '09 19:03

CodeMonkeyKing


People also ask

Which is null coalescing operator?

The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.

Why we use null coalescing operator?

operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.

What is Elvis operator in C#?

In certain computer programming languages, the Elvis operator, often written ?: , or or || , is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand.

When was Nullish coalescing operator added?

JavaScript made sure this can be handled with its nullish operator also known as the Null Coalescing Operator, which was added to the language with ECMAScript 2020. With it, you can either return a value or assign it to some other value, depending on a boolean expression.


2 Answers

Other programming languages like Ruby use this quite frequently:

something ||= Something.new 
like image 133
Bob Aman Avatar answered Sep 28 '22 05:09

Bob Aman


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());     } } 
like image 43
phil Avatar answered Sep 28 '22 05:09

phil