Friday, June 11, 2010

Operator ? trick

Conditional operator (?:) raise error CS0173 when trying to assign null to a nullable type

After defining a variable of a nullable type, when trying to assign it through a conditional operator, if I try to assign , the complier throw me an error (error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'int'), while I was waiting it to be able to implicitly convert between to . Reading the error description, it looks that the compiler is trying to cast between to , so something is probably going wrong, also 'cause If I expand the conditional operator in the equivalent if .. else .., everything goes fine.






By design. Conditional operator can figure out correct return type only in case if one side of expression can be implicitly converted to another.
int and null type can not be converted in any direction.
To demonstrate this - you must be aware that there are 2 workarounds - not one.
yours


int? a = true ? (int?) null : 12;
as well
int? a = true ? null : (int?)12;
This will make following pairs of types - int? and int and null type and int?. 


Something I agree - since null-type is special case and very used often - this will be nice to make it special in this situation also.

No comments:

Post a Comment