Вопрос

Just reading up on the specs for this operator ?? as it takes the left side and, if null returns the value on the right side.

My question is, can I have it return 3 possible values instead?

Something like this:

int? y = null;
int z = 2;

int x = y ?? (z > 1 ? z : 0);

Is this possible?

Это было полезно?

Решение

Absolutely - you could use ?? in the same way as any other binary operator, meaning that you could have any expression on its left and/or on its right.

For example, you could do something like this:

int? a = ...
int? b = ...
int? c = ...
int? d = ...
int? res = (condition_1 ? a : b) ?? (condition_2 ? c : d);

This expression will evaluate (condition_1 ? a : b) first, check if it's null, and then either use the non-null value as the result, or evaluate the right-hand side, and us it as the result.

You can also "chain" the null coalesce operators ??, like this:

int? res =a ?? b ?? c ?? d;

Evaluation of this expression goes left to right.

Другие советы

The ?? is a binary operator, but the second operand (the right hand side) can be any expression you want (as long as it has a suitable return type to be coalesced with the first operand). So yes, the second operand can be (z > 1 ? z : 0). That doesn't make the ?? have 3 possible return values.

Your code is perfectly legit as is. You can also do something like:

int x = a ?? b ?? c;

Yes it 's possible. Try to compile and make some test you should verify by yourself.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top