1. Null-Conditional Operator
Null-Conditional Operator is available from C# 6.0 which makes more readable way of comparing the null object. The operator ‘?.’
is called Null-Conditional Operator. Some programmer calls this operator as Elvis Operator. In this example, we will see how to use this operator to check for the null objects.
2. Null Objects to Test Null-Conditional
When C# CLR allocates memory for an object, the object reference holds the heap location of the memory. Now look at the below code in which the String object str1 is holding the location which stores the letters Abc123. Second string object str1 is empty or it is marked with Null. In this example, we will use these two strings to see how to use the Null-Conditional operator.

3. Checking Null Objects the Old Way
Before C# 6.0, we check the null object using the comparison operators ‘==
’ or ‘!=
’. The below code shows testing the null object in a traditional way:

Explanation
- Here, in this code snippet we use the != operator to check str1 is not null and holding some value.
- The null check is followed by one more condition to see it contains at least one character. So, we use the property Length. Note, the null conditional check which we kept as a first conditional check makes it safer to access the Length property. But when a programmer mistakenly keeps the Length check before checking the null, there will be a runtime error when object is null.
- We check our second string the same way and when both the conditions return true, WriteLine method prints the content of the second string.
4. Null-Conditional (or) Elvis Operator
Now, let us use the Null-Conditional Operator (?.
) to check for the Null objects. The below code snippet shows checking the null object using Elvis operator.

Explanation
- The Elvis Operator (Null-Conditional) operator
?.
is used on the object str1. When the object str1 is not null, the operator then invokes theLength
property. This reduces the code which performs two conditional checks as in our previous example. - The same way, we perform second conditional check on the str2 object.
5. Code Reference
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CAshExamples { class Program { static void Main(string[] args) { //Sample 01: Define a String String str1 = "Abc123"; String str2 = null; //Sample 02: Check for Null Old Way if (str1 != null && str1.Length > 0) Console.WriteLine("Content of String 1: " + str1); if (str2 != null && str2.Length > 0) Console.WriteLine("Content of String 2: " + str2); //Sample 03: Check for Null Modern Way if (str1?.Length > 0) Console.WriteLine("Content of String 1: " + str1); if (str2?.Length > 0) Console.WriteLine("Content of String 2: " + str2); } } } |
Categories: C#
Tags: ?. Operator, Elvis Operator, Null-Conditional Operator