Null-coalescing operator in C#

You can use the null-coalescing operator (??) to provide a default value for a nullable type or reference type.

The null-coalescing operator returns the left-hand operand if it is not null, or the right-hand operand if the left-hand operand is null.

Here is an example of how to use the null-coalescing operator:

string s = null;
string s2 = s ?? "default value";  // s2 is "default value"

This is equivalent to the following code:

string s = null;
string s2;
if (s != null)
{
    s2 = s;
}
else
{
    s2 = "default value";
}

The null-coalescing operator is a shorthand way to provide a default value for a nullable or reference type. It can make your code more concise and easier to read.


Enjoyed this post? Subscribe to my YouTube channel for more great content. Your support is much appreciated. Thank you!


Check out my Udemy profile for more great content and exclusive learning resources! Thank you for your support.
Ervis Trupja - Udemy



Enjoyed this blog post? Share it with your friends and help spread the word! Don't keep all this knowledge to yourself.