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,737
  • 4
  • 41
  • 56

3 Answers3

1

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

Justin Niessner
  • 236,029
  • 38
  • 403
  • 530
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,638
  • 10
  • 18
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
  • 85,597
  • 17
  • 118
  • 137