0

Possible Duplicate:
Is there an “opposite” to the null coalescing operator? (…in any language?)

Is there a more concise way of writing the third line here?

int? i = GetSomeNullableInt();
int? j = GetAnother();
int k = i == null ? i : j;

I know of the null coalescing operator but the behaviour I'm looking for is the opposite of this:

int k == i ?? j;
Community
  • 1
  • 1
Nick Strupat
  • 4,928
  • 4
  • 44
  • 56

3 Answers3

1

In C#, the code you have is the most concise way to write what you want.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

Sneaky - you edited it while I was replying. :)

I do not believe there is a more concise way of writing that. However, I would use the "HasValue" property, rather than == null. Easier to see your intent that way.

int? k = !i.HasValue ? i : j; 

(BTW - k has to be nullable, too.)

Wesley Long
  • 1,708
  • 10
  • 20
1

What is the point of that operator? The use cases are pretty limited. If you're looking for a single-line solution without having to use a temporary variable, it's not needed in the first place.

int k = GetSomeNullableInt() == null ? null : GetAnother();
Jimmy
  • 89,068
  • 17
  • 119
  • 137