0

Imagine situation

int? customerId = null; // works fine
int? customerId = 5; // also fine
int? customerId = someCondition ? 5 : null; // There is no implicit conversion between int and null
int? customerId = someCondition ? 5 : (int?)null; // now is ok

How is this possible? Is it the language specification? For me the obvious would be implicit conversion. What do you think?

stanke
  • 276
  • 2
  • 13
  • My guess is that there is not implicit conversion between int and null because int is a value type and not an object type. – Zohar Peled Mar 31 '15 at 08:38
  • This has been asked many times before. `a?b:c`'s result type will be either the type of `b`, or the type of `c`. If neither of those types is possible, your code has an error. Let me find a duplicate. –  Mar 31 '15 at 08:38
  • I agree but there is nullable int as l-value type – stanke Mar 31 '15 at 08:39
  • `Nullable` has implemented the implicit and explicit operator for type convertion, but not `null` https://msdn.microsoft.com/en-us/library/ff986458(v=vs.110).aspx – Eric Mar 31 '15 at 08:40
  • @stanke Neither the second nor the third operand of your failing `?:` expression has type `int?`, so type `int?` is not considered. –  Mar 31 '15 at 08:40
  • @hvd, I didn't know how to search for this. Thanks for the quick answer! – stanke Mar 31 '15 at 08:42

0 Answers0