In C#, two question marks together (??) represent the null-coalescing operator. The null-coalescing operator is used to provide a concise way to handle null values and perform a fallback action or provide a default value when a nullable expression evaluates to null. It is particularly useful for handling null reference exceptions and simplifying null checks.
The syntax of the null-coalescing operator is as follows:
expression1 ?? expression2
Here’s how it works:
expression1
is not null, the result of the expression is the value of expression1
.expression1
is null, the result of the expression is the value of expression2
.Here are multiple examples to illustrate its usage:
int? nullableInt = null;
int nonNullableInt = nullableInt ?? 42;
Console.WriteLine(nonNullableInt); // Output: 42
In this example, nullableInt
is assigned the value of null
. When using the null-coalescing operator, since nullableInt
is null, the default value 42
is used for nonNullableInt
.
string nullableString = null;
string nonNullableString = nullableString ?? "Hello, world!";
Console.WriteLine(nonNullableString); // Output: Hello, world!
Here, nullableString
is null, so the null-coalescing operator replaces it with the default string "Hello, world!"
.
class Person
{
public string Name { get; set; }
}
Person nullablePerson = null;
Person nonNullablePerson = nullablePerson ?? new Person { Name = "John Doe" };
Console.WriteLine(nonNullablePerson.Name); // Output: John Doe
In this example, nullablePerson
is null, so the null-coalescing operator creates a new Person
instance with the name “John Doe” and assigns it to nonNullablePerson
.
string firstName = null;
string lastName = "Doe";
string fullName = firstName ?? "John" ?? lastName ?? "Unknown";
Console.WriteLine(fullName); // Output: John
In this case, the first non-null value in the chain is "John"
, so fullName
is assigned the value "John"
.
The null-coalescing operator is a powerful tool for handling null values in a concise manner, making code more readable and less prone to null reference exceptions. Keep in mind that expression1
and expression2
must be compatible types or implicitly convertible to each other, or else a compile-time error will occur.