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.
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.
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.
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.
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.
Other programming languages like Ruby use this quite frequently:
something ||= Something.new
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()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With