Null-coalescing operator in C#
gpeipman
30.4K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Null-coalescing operator
Null-coalescing operator (??) is convenient shortcut to return some other value when variable or expression is null.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
}
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content