Safe Assignment (?=) Expression

Summary

Assigns the first non-null, non-undefined value to a variable.

Syntax

variable ?= expression

Parameters

variable
The variable, property, or array element to update.
expression
Any legal expression.

Description

The safe assignment operator (?=) computes the value of the expression on the right; compares it to the variable, property, or array element on the left; and, finally, assigns the first non-null, non-undefined value back to the variable, property, or array element on the left. Therefore, if the variable, property, or array element on the left is already not null and not undefined, it will simply retain its value. The expression on the right is evaluated prior to assignment.

1
2
3
int? x = 2, y = null;
x ?= 5; // x remains 2
y ?= 5; // y is now 5

If both sides of the safe assignment operator evaluate to null, the value for the variable will remain null. If both sides of the safe assignment operator evaluate to undefined, the value for the variable will remain undefined.

The safe assignment operator applies to both existent types and nullable types.

Examples

Using the safe assignment operator to assign a non-null value
1
2
3
4
5
6
import System;
 
int? x = null;
Console.log(x); // null
x ?= 5;
Console.log(x); // 5
Example with existent types
1
2
3
4
5
import System;
 
int[] arr = [ 1, 2, 3 ];
int+ x = arr[Math.random(100)];
x ?= 5; // Possible values for x: 1, 2, 3, 5

Share

HTML | BBCode | Direct Link