#211 – Using the Null-Coalescing (??) Operator

In C#, the ?? operator, know as the null-coalescing operator, is often used with nullable types.

The ?? operator is used in an expression of the form:

            operand ?? nullval

This expression evaluates to:

  • operand, if operand is non-null
  • nullval, if operand is null

The operand is a variable and the nullval is a variable or constant of the same type as the variable.

The ?? operator is generally used where you have a nullable type and you want to assign its value to a non-nullable type.  Since the nullable type can have the value of null, you need to specify what non-null value to assign in that case.

Here’s an example:

            uint? age = null;   // Nullable age -- might not have a value

            // Later: assign to a non-nullable uint.
            //   Store the age (if non-null)
            //   Store 0  (if null)
            uint ageStore = age ?? 0;

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: