Can someone please explain me the logic reason why I must cast null to int?
When the left argument type can have their both types ?
Insted of doing
int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : null);
I must do
int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);
although int? k = null is perfectly valid.
An opposite example :
I didn’t have to do it in:
string k = (DateTime.Now.Ticks%5 > 3 ? "lala" : null);
In this case what we have is 1 is
intandnullis actuallynullNow the confusion is the ternary operator is confused as what is the return type
intor wellnulland since itsintit won’t acceptnullSo you would need to cast it to a nullable
intNow in the other case you have a string and null is perfectly acceptable for a
stringFurther explanation can be found at Type inference – Eric