I am a C# newbie and I just encounter a problem. There is a difference between C# and Java when dealing with the ternary operator (? :
).
In the following code segment, why does the 4th line not work? The compiler shows an error message of there is no implicit conversion between 'int' and 'string'
. The 5th line does not work as well. Both List
s are objects, aren't they?
int two = 2;
double six = 6.0;
Write(two > six ? two : six); //param: double
Write(two > six ? two : "6"); //param: not object
Write(two > six ? new List<int>() : new List<string>()); //param: not object
However, the same code works in Java:
int two = 2;
double six = 6.0;
System.out.println(two > six ? two : six); //param: double
System.out.println(two > six ? two : "6"); //param: Object
System.out.println(two > six ? new ArrayList<Integer>()
: new ArrayList<String>()); //param: Object
What language feature in C# is missing? If any, why is it not added?