Older C# features
This section covers a list of C# features that are useful, less known, or I want to make sure you are aware of since we are leveraging or mentioning them in the book.
The null-coalescing operator (C# 2.0)
The null-coalescing (??
) operator is a binary operator written using the following syntax: result = left ?? right
. It expresses to use the right
value when the left
value is null
. Otherwise, the left
value is used.
Here is a console application using the null-coalescing operator:
Console.WriteLine(ValueOrDefault(default, "Default value"));
Console.WriteLine(ValueOrDefault("Some value", "Default value"));
static string ValueOrDefault(string? value, string defaultValue)
{
return value ?? defaultValue;
}
The ValueOrDefault
method returns defaultValue
when value
is null
; otherwise, it returns value
. Executing that program outputs the following:
Default value
Some value
The null-coalescing (??
) operator...