C# Null Coalescing and Null Conditional Operators

This C# article examines the null coalescing operator. It tests the performance of this operator.

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.

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.PropertyNull

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.

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


Above, the Name property will never return null. If the "_name" is null, it return the string "Default". Calling code does not need to check against null.

And: You can always use an expression like Name.Length, because Name will never return null. NullReferenceException is never thrown.



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.

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

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.Nullable IntNullable BoolNullable DateTime


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.

Tip: 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

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.Ternary Operator
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen,