Welcome! Spanish articles on LinkedIn. You can follow me on Twitter for news.
What is null-coalescing?
According to ms docs, the null-coalescing operator ??
returns the value of its left-hand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator does not evaluate its right-hand operand if the left-hand operand evaluates to non-null.
Through a Youtube video, I'll show how to use the null coalescing operator in C# 8.0 and the evolution of this:
- Old way
- With C# 7
- Finally with C# 8.0
Example
We have a variable called age with a null value
static int? GetNullAge() => null;
static int? GetAge() => 27;
int? age = GetNullAge();
Old way
We need to check if the value is null and then assign the value
if (age == null)
{
age = GetAge();
}
C# 7
We use the null coalescing operator
age = age ?? GetAge();
C# 8.0
We use the compound assignment operator
age ??= GetAge();
For more information:
Youtube video
Github GIST
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
static int? GetNullAge() => null; | |
static int? GetAge() => 27; | |
int? age = GetNullAge(); | |
//Old Way | |
//if (age == null) | |
//{ | |
// age = GetAge(); | |
//} | |
//C# 7 | |
//age = age ?? GetAge(); | |
//C# 8.0 | |
age ??= GetAge(); | |
Console.WriteLine(age); | |
Console.ReadLine(); | |
} | |
} |
Top comments (1)
Nitpicking: The null coalescing operator (
??
) was around in c# 6 as well, and if memory serves, perhaps even also in c# 5. The null-coalescing assignment operator (??=
) is new, though.