Given the following routine:
private static object ParseNumber(string token, FieldDefinition def) { if (def.Fraction > 0) return Double.Parse(token); else return Int64.Parse(token); }
Resharper offers me the option to refactor it into a statement with the ternary operator:
private static object ParseNumber(string token, FieldDefinition def) { return def.Fraction > 0 ? Double.Parse(token) : Int64.Parse(token); }
Who can spot the trap?
Okay, change to previous answer. Because there’s an implicit conversion from
Int64toDouble(but not vice versa), that will be the result type of the expression. So when you expect to get a boxedInt64, you actually get a boxedDouble(but with a value which originally came fromInt64.Parse).Just in case that’s not clear enough, let’s change all the
returnstatements such that they just return a variable. Here’s the original code:Convert that appropriately:
And now let’s do the same to the version with the conditional operator:
becomes
EDIT: As requested, a bit more information. The type of a conditional expression of the form
depends on the types of
YandZ, which I’ll callTYandTZ. There are a few options:TYandTZare the same type: result is that typeTYtoTZbut not fromTZtoTY: the result is of typeTZand the conversion is used if the first branch is used.TZtoTYbut not fromTYtoTZ: the result is of typeTYand the conversion is used if the second branch is used.Does that help?