#213 – Final Operand When Using Null-Coalescing (??) Operator

You can use several ?? (null-coalescing) operators in a single expression.  For example:

    int result = i ?? j ?? k ?? 0;    // i, j and k are all of type int?

Notice that the final operand in the long expression is an integer constant.  If we tried to use an int? variable as the final operand, we’d get a compile-time error indicating that we can’t implicitly convert the int? to an int.  (Because the int? variable might be null, which can’t be assigned to an int).

    int result = i ?? j ?? k;    // Compile-time error

Whenever you use this form of an expression with the ?? operator, assigning a value to a non-nullable type, the type of the 2nd operand must match the type of the variable being assigned to.  (Or be implicitly converted to the target type).

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 )

Google photo

You are commenting using your Google 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: