Handling Empty Data with Null Operators

Handling Empty Data with Null Operators

Something is considered to be null when it has no value. In this case, we are looking at how C# handles the possibility of variables being null. Values being null can be a very common cause of software encountering issues so implementing these null operators will help to make your software more robust.

Null reference goes to nothing

There are two null operators in C#, the Null-conditional Operator and the Null Coalescing Operator.

Null-Condition Operator

The null condition operator helps in circumstances where it is not known if the operand is null when trying to access its members. To use the null conditional operator place a “?’ Immediately after an operand, before any calls to members.


using System;

public class Program
{
	public static void Main()
	{
		string x = null;
		Console.WriteLine(x?.ToUpper()); // No Error

		Console.WriteLine(x.ToUpper());  // Error
	}
}
                

For example, if you were trying to access the colour member of a Car object that did not exist, you would normally get a NullReferenceException. By using this operator, you would now get a null instead.

This operator will also affect all subsequent member calls from the object. For example, if you wished to get the colour member and then make an additional call to ToString(), you would not need to include another ?. This is valid unless the final value is a type which cannot take on a null value such as an integer.


using System;

public class Program
{
	public static void Main()
	{
		string x = null;
		Console.WriteLine(x?.ToUpper().ToString()); // No Error

		Console.WriteLine(x.ToUpper().ToString());  // Error
	}
}
                

You can also use the null conditional operator whilst calling a void method, no operation will happen but there will not be a NullReferenceError.

Null Coalescing Operator

The Null Coalescing operator checks to see if a provided value is not null, if that is the case then the result on the left is given, if it is null then the default value from the right is provided.


using System;

public class Program
{
	public static void Main()
	{
		string s1 = null;
		var s2 = s1 ?? "The string s1 was null";

		Console.WriteLine(s2);
	}
}