3

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?

Solomon Closson
  • 6,111
  • 14
  • 73
  • 115

4 Answers4

2

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

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

int x = a ?? b ?? c;
Paul
  • 5,700
  • 5
  • 43
  • 67
2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I don't understand the chaining for this... how does that work. Do you have to have `int?` with a question mark at the end of `int` in order for it to work that way? – Solomon Closson Apr 15 '14 at 13:32
  • 1
    @SolomonClosson `??` expression requires a nullable on its left-hand side, so in my example above `a`, `b`, and `c` must be `int?`; `d` could be `int?` or `int`. Chained expression is evaluated left-to-right - first, `a??b`, then `(a??b)??c`, then `((a??b)??c)??d`. – Sergey Kalinichenko Apr 15 '14 at 13:35
  • Curious, what if I wanted to do this to a `Dictionary` in order to put default values in if a key is not found? Would it be done like this: `Dictionary myDictionary = new Dictionary();` and than would I be able to do this: `string theKey = myDictionary["keyNotinDictionary"] ?? "Not Found";`?? – Solomon Closson Apr 16 '14 at 17:19
  • 1
    @SolomonClosson No. First, `Dictionary` is a reference type, i.e. it's already nullable, so you do not need `??`. Second, when a key is not there and you call `dict[...]`, `Dictionary` throws an exception. Unfortunately, you cannot do it in one line - the best you can do is two lines: `string res; string theValue = myDictionary.TryGetValue("keyNotinDictionary", out res) ? res : "Not Found";` – Sergey Kalinichenko Apr 16 '14 at 17:23
1

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

Gaston Siffert
  • 372
  • 1
  • 8