Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Null-Conditional Operator in C#

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.

Fig 1. String With Null Value
Fig 1. String With Null Value

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:

Fig 2. Checking For Null Old Way
Fig 2. Checking For Null Old Way


  1. Here, in this code snippet we use the != operator to check str1 is not null and holding some value.
  2. 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.
  3. 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.

Fig 3. Using Elvis Operator
Fig 3. Using Elvis Operator


  1. The Elvis Operator (Null-Conditional) operator ?. is used on the object str1. When the object str1 is not null, the operator then invokes the Length property. This reduces the code which performs two conditional checks as in our previous example.
  2. The same way, we perform second conditional check on the str2 object.

5. Code Reference

Categories: C#

Tags: , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.