Null Coalescing and Null Conditional OperatorsExamine the null coalescing and null conditional operators. Measure performance against if.
This page was last reviewed on Jan 25, 2022.
Null coalescing. The null coalescing operator "??" uses 2 question marks. With it you can use a custom value for a null reference variable. It simplifies null tests.
Null conditional. Similar to the coalescing operator, the null conditional operator tests for null before accessing a member of an instance.
First example. The null coalescing operator is useful inside properties. Often, a property that returns an object (such as a string) may be null. This null value complicates things.
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.
Detail 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.
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); } }
Default Perls Default
Null-conditional. Let's examine the null-conditional operator. The Test() method here receives a string called "name." If name is null, the Length property will not be accessed.
However If name is not null, we check Length as expected. With this operator we reduce our if-statements to combine two logical checks.
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. } }
1 2 True True
Benchmark. I tested the null coalescing operator in an assignment statement. I tested it against an if-statement equivalent. I found both constructs had similar (or the same) performance.
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.
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")); } }
0.71 ns, If-else statement 0.69 ns, Null coalescing
Value types. You cannot use the null coalescing operator on value types such as int or char. But with nullable types, such as "int?" or "char?" you can use the "??" operator.
A summary. We used the null coalescing operator. With this operator, you can handle null references with less source code. The null coalescing operator is similar to the ternary operator.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 25, 2022 (edit).
© 2007-2024 Sam Allen.