C# Language Null-Coalescing Operator Basic usage

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Using the null-coalescing operator (??) allows you to specify a default value for a nullable type if the left-hand operand is null.

string testString = null;
Console.WriteLine("The specified string is - " + (testString ?? "not provided"));

Live Demo on .NET Fiddle

This is logically equivalent to:

string testString = null;
if (testString == null)
{
    Console.WriteLine("The specified string is - not provided");
}
else
{
    Console.WriteLine("The specified string is - " + testString);
}

or using the ternary operator (?:) operator:

string testString = null;
Console.WriteLine("The specified string is - " + (testString == null ? "not provided" : testString));


Got any C# Language Question?