What do two question marks together mean in C#?

Post author: Adam VanBuskirk
Adam VanBuskirk
7/29/23 in

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:

  1. If expression1 is not null, the result of the expression is the value of expression1.
  2. If expression1 is null, the result of the expression is the value of expression2.

Here are multiple examples to illustrate its usage:

Example 1: Using the null-coalescing operator with non-nullable types:

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.

Example 2: Using the null-coalescing operator with strings:

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!".

Example 3: Using the null-coalescing operator with custom classes:

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.

Example 4: Combining multiple null-coalescing operators:

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.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *

Read Next

© 2024 Menyu LLC