Difference between C# and Java's ternary operator (? :) -
i c# newbie , encounter problem. there difference between c# , java when dealing ternary operator (? :).
in following code segment, why 4th line not work? compiler shows error message of there no implicit conversion between 'int' , 'string'. 5th line not work well. both lists objects, aren't they?
int 2 = 2; double 6 = 6.0; write(two > 6 ? 2 : six); //param: double write(two > 6 ? 2 : "6"); //param: not object write(two > 6 ? new list<int>() : new list<string>()); //param: not object however, same code works in java:
int 2 = 2; double 6 = 6.0; system.out.println(two > 6 ? 2 : six); //param: double system.out.println(two > 6 ? 2 : "6"); //param: object system.out.println(two > 6 ? new arraylist<integer>() : new arraylist<string>()); //param: object what language feature in c# missing? if any, why not added?
looking through c# 5 language specification section 7.14: conditional operator can see following:
if x has type x , y has type y then
if implicit conversion (§6.1) exists x y, not y x, y type of conditional expression.
if implicit conversion (§6.1) exists y x, not x y, x type of conditional expression.
otherwise, no expression type can determined, , compile-time error occurs
in other words: tries find whether or not x , y can converted eachother , if not, compilation error occurs. in our case int , string have no explicit or implicit conversion won't compile.
contrast java 7 language specification section 15.25: conditional operator:
- if second , third operands have same type (which may null type), type of conditional expression. (no)
- if 1 of second , third operands of primitive type t, , type of other result of applying boxing conversion (§5.1.7) t, type of conditional expression t. (no)
- if 1 of second , third operands of null type , type of other reference type, type of conditional expression reference type. (no)
- otherwise, if second , third operands have types convertible (§5.1.8) numeric types, there several cases: (no)
- otherwise, second , third operands of types s1 , s2 respectively. let t1 type results applying boxing conversion s1, , let t2 type results applying boxing conversion s2.
type of conditional expression result of applying capture conversion (§5.1.10) lub(t1, t2) (§15.12.2.7). (yes)
and, looking @ section 15.12.2.7. inferring type arguments based on actual arguments can see tries find common ancestor serve type used call lands object. object is acceptable argument call work.
Comments
Post a Comment