There are two different types of null operators available in C#; those are the Null coalescing operator and Null conditional operator. Null conditional operator introduced in C# 6.0.
Null Coalescing Operator: The null coalescing operator indicated by ?? symbol in C#. It is a conditional operator which is used to compare the variable value with null. This operator returns a default value if the variable is null. Otherwise, it returns variable value.
To check this open Microsoft Visual Studio and create a C# console application and add below code.
using System;
namespace CSharpNullOperators
{
class Program
{
static void Main(string[] args)
{
string str1 = null;
string result1 = str1 ?? "No Value";
string str2 = "This is String Variable";
string result2 = str2 ?? "No Value";
Console.WriteLine("result1: " + result1);
Console.WriteLine("result2: " + result2);
Console.ReadLine();
}
}
}
As shown above, we have a null value for variable str1, so result1 returns value as “No Value”. Whereas result2 returns str2 variable value because str2 contains non-null value as shown below.
Null Conditional Operator: Null Conditional operator introduced in C# 6.0. Before C# 6.0 if you want to convert any object value into a string first you have to check whether the object is null or not as shown below. Without the null validation, it returns “Object reference returns to an instance of object” error if the object contains a null value.
Before C# 6.0
class Program
{
static void Main(string[] args)
{
object obj = null;
string result = (obj == null ? null : obj.ToString());
}
}
In C# 6.0, we have new operator called null conditional operator or Elvis operator which allows us to call any string method even though variable contains null value. If variable contains null value, it will not apply any string method else it applies as shown below.
using System;
namespace CSharpNullOperators
{
class Program
{
static void Main(string[] args)
{
object obj1 = null;
string result1 = obj1?.ToString().ToLower();
string obj2 = "This is String Variable";
string result2 = obj2?.ToString().ToLower();
Console.WriteLine("result1: " + result1);
Console.WriteLine("result2: " + result2);
Console.ReadLine();
}
}
}
Here first object obj1 has a null value, so no string method applies on it, and it returns no error bcecause we are using null conditional operator here. The result result1 displays the empty value. Object obj2 conatins non-null value, so it converts the string into the lower case as shown below.
We can apply
null conditional operators on any C# type to check for null value.