Null coalescing: The null coalescing operator “??” uses two question marks. With it you can use a custom value for a null reference variable. It simplifies null tests.
C# program that uses null coalescing operator
using System;
class Program
{
static string _name;
/// <summary>
/// Property with custom value when null.
/// </summary>
static string Name
{
get
{
return _name ?? "Default";
}
set
{
_name = value;
}
}
static void Main()
{
Console.WriteLine(Name);
Name = "Perls";
Console.WriteLine(Name);
Name = null;
Console.WriteLine(Name);
}
}
Output
-------
Default
Perls
Default
Null conditional: Similar to the coalescing operator, the null conditional operator tests for null before accessing a member of an instance.
C# program that uses null-conditional operator
using System;
class Program
{
static void Test(string name)
{
// Use null-conditional operator.
// ... If name is not null, check its Length property.
if (name?.Length >= 3)
{
Console.WriteLine(true);
}
}
static void Main()
{
Console.WriteLine(1);
Test(null);
Console.WriteLine(2);
Test("cat"); // True.
Test("x");
Test("parrot"); // True.
}
}
Output
-------
1
2
True
True
