Almost 5 years ago I made a post on the null conditional operator (?:) in C#. Now I am following up with a series on different operators. This post is on the Null-coalescing assignment operator (??=).
The null-coalescing assignment operator makes it easy to assign a new value to a variable if it is null. It checks the left side operand and if it is null it assigns the right side operand to it. An example of this can be seen below where s
is "SomeValue"
and k
is null therefore k
becomes "SomeValue" when the
??=` operator is used:
string s = "SomeValue";
string k = null;
k ??= s;
Assert.Equal("SomeValue", k);
Had k
not been null it would have kept its value:
string s = "SomeValue";
string k = "AnotherValue";
k ??= s;
Assert.Equal("AnotherValue", k);
I hope you found this post on the ??= operator helpful, let me know what you think in the comments down below :)
More on operators from my blog: