C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: It is sometimes clearer to have code inside the property that handles null values and returns a custom value in that case.
Tip 2: This is simple to do with the "??" operator. This example demonstrates a null coalescing property.
Name: The Name property will never return null. If the "_name" is null, it return the string "Default".
And: You can always use an expression like Name.Length, because Name will never return null. NullReferenceException is never thrown.
NullReferenceExceptionC# 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
However: If name is not null, we check Length as expected. With this operator we reduce our if-statements to combine two logical checks.
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
Version 1: This version of the code uses an if-statement. If the first string is null, we use the value "result."
Version 2: This code does the same thing as version 1, but uses the null coalescing operator.
Result: This performance test is not perfect—it only tests a null value. But it tends to support that the operator is fast.
C# program that benchmarks null coalescing
using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
string value = null;
var s1 = Stopwatch.StartNew();
// Version 1: test if-else statement.
for (int i = 0; i < _max; i++)
{
string result;
if (value != null)
{
result = value;
}
else
{
result = "result";
}
if (result.Length != 6)
{
return;
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use null coalescing operator for assignment.
for (int i = 0; i < _max; i++)
{
string result = value ?? "result";
if (result.Length != 6)
{
return;
}
}
s2.Stop();
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.Read();
}
}
Output
0.71 ns, If-else statement
0.69 ns, Null coalescing