C# - What is the "??" null-coalescing operator?

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 operator (??).

The null-coalescing operator makes it easy to check if a variable is null and if it is null, return a different value. It checks the left side operand and if it is null it evaluates the right side operand and returns that instead, if the left side is not null it never evaluates the right side but returns the value on the left. An example of this can be seen below where s is null and therefore k does not become null:

string s = null;
var k = s ?? "";
Assert.NotNull(k);

If s is not null, it returns the value of s instead:

string s = "";
var k = s ?? null;
Assert.Equal("", 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: