An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
July 19, 2021 06:14 pm GMT
Original Link: https://dev.to/sheikh_ishaan/null-coalescing-operator-in-c-4cjk
Null Coalescing Operator in C
If you have used javascript before you probably have used the logical OR (||) operator while assigning values to a variable. For example,
let a = b || c;
The above code snippet assigns the value of b
to a
if it is defined, else assign c
to it.
In C# the ??
operator is used to handle this kind of situations.
This operator us available in C# 8.0 and later.
Syntax
a = b ?? c;
The above statement will be equivalent to
if(b == null){ a = c}else{ a = b}
Examples
Below are some use-cases for ??
operator.
1. Throwing an exception
int? val = input ?? throw new Exception("'input' cannot be null");
2. Assigning a default value
int? requiredValue = userInput ?? -1;
3. This operator can also be Nested
int? a = 1;int? b = null;int? c = 3;int? d = a ?? b ?? c;Console.Write(d); // 1
This operator is right-associative, so the above example will evaluated as
a ?? (b ?? c)a ?? (null ?? 3)a ?? 31 ?? 31
Original Link: https://dev.to/sheikh_ishaan/null-coalescing-operator-in-c-4cjk
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To