null Coalescing (??) Operator
The null coalescing operator (??) could be a binary operator that determines among the 2 operands, that area unit or can manufacture a non-null worth. this is often generally used for defaulting functions. Below is that the syntax for victimization the null coalescing operator.
var result = operand1 ?? operand2;
operand1 and operand2 can be a variable, method call, or expression. If operand1 is a variable has a null value or an expression or method call that produces a null value, then it looks at the value of operand2 instead. If operand2 is not null, then it’s value is used to assign to result.
public class Program
{
public static void Main(string[] args)
{
int? num1 = null;
int? num2 = 100;
int? num3 = num1 ?? num2;
Console.WriteLine($"Value is {num3}");
}
}
Example 1 – Using the null Coalescing Operator
Value is 100
In Example 1, we used the null coalescing operator in line 8. Since we initially assigned a null value to num1 and num2 has a non-null value, the value of num2 will be used to be assigned to num3.
Here is another example which calls a method that we don’t have certainty until runtime whether it will return null or not.
using System;
namespace NullCoalescingOperator
{
public class Program
{
public static void Main(string[] args)
{
Random randomizer = new Random();
int? result = GetNullOrIntValue(randomizer.Next(1, 10)) ?? default(int);
Console.WriteLine($"Result is {result}");
}
public static int? GetNullOrIntValue(int randomValue)
{
if (randomValue % 2 == 0)
{
return null;
}
return 100;
}
}
}
Example 2 – A more practical use of null coalescing operator
Result is 100
Result is 0
In Example 2, we defined a method named GetNullOrIntValue that accepts a random value. This method will return null if the passed argument is even, otherwise, it will return 100 as value. Once we call this method in line 11, we randomized a number and passed it as an argument. The second operand we used for the null coalescing operator uses the default keyword to determine the default value of type int which is 0. If the method call returned null because the randomized value passed is even, then it will use the default value of the int, otherwise, it will use the returned non-null value of the method. This is one example of defaulting. If you cannot allow null values in your subsequent code, then we default it to some other value.