What is the most concise way to write the opposite of a null coalesce [duplicate]
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 coalesci开发者_开发知识库ng operator but the behaviour I'm looking for is the opposite of this:
int k == i ?? j;
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.)
In C#, the code you have is the most concise way to write what you want.
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();
精彩评论