The null-coalescing
operator
??
returns the value
of its left-hand operand if it isn't null
; otherwise, it evaluates the right-hand operand and returns its
result. The ??
operator doesn't
evaluate its right-hand operand if the left-hand operand evaluates to non-null.
Available in
C# 8.0 and later, the null-coalescing assignment operator
??=
assigns the value
of its right-hand operand to its left-hand operand only if the left-hand
operand evaluates to null
. The ??=
operator doesn't evaluate its right-hand operand if the
left-hand operand evaluates to non-null.
Example 1:
List<int>
numbers = null;
int? a = null;
(numbers ??= new List<int>()).Add(5);
Console.WriteLine(string.Join(" ", numbers)); // output: 5
numbers.Add(a ??= 0);
Console.WriteLine(string.Join(" ", numbers)); // output: 5 0
Console.WriteLine(a); // output: 0
Example 2:
double SumNumbers(List<double[]> setsOfNumbers, int indexOfSetToSum)
{
return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? double.NaN;
}
var sum = SumNumbers(null, 0);
Console.WriteLine(sum); // output: NaN
Example 3:
public string Name
{
get => name;
set => name = value ??
throw new ArgumentNullException(nameof(value), "Name cannot be null");
}
No comments:
Post a Comment