Null-coalescing operator in C#

gpeipman
6,348 views
undefined

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Null-coalescing operator

Null-coalescing operator (??) is convenient shortcut to return some other value when variable or expression is null.

using System;
class Hello
{
static void Main()
{
string text1 = null;
string text2 = "replacement text";
string textToWrite = null;
// long version
if(text1 == null)
{
textToWrite = text2;
}
else
{
textToWrite = text1;
}
Console.WriteLine(textToWrite);
// shorter version
textToWrite = text1==null ? text2 : text1;
Console.WriteLine(textToWrite);
// minimal version
textToWrite = text1 ?? text2;
Console.WriteLine(textToWrite);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content