Search code examples
c#asp.netoperatorscoalescing

C# coalescing operator with 3 possible return values?


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?


Solution

  • 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.