Reputation: 428
static void test(bool b)
{
int i = 1; char c = (char)65;
string s; if (b) s = "blubb" + i; else s = "blubb" + c;
string t = "blubb" + (b ? i : c);
Console.WriteLine(s + " == " + t);
}
The call test(true) gives "blubb1 == blubb1".
The call test(false) gives "blubbA == blubb65".
Additional Question
Edited:
static void test(bool b)
{
int i = 1; char c = (char)65;
string s; if (b) s = "blubb" + i; else s = "blubb" + c;
string t = "blubb" + (b ? i : c);
string u = "blubb" + (b ? c : i);
Console.WriteLine(s + " == " + t + " == " + u);
}
The call test(true) gives "blubb1 == blubb1 == blubb65".
The call test(false) gives "blubbA == blubb65 == blubb1".
What explains this unexpected behavior?
Upvotes: 2
Views: 86
Reputation: 7309
This is the key line
string t = "blubb" + (b ? i : c);
As i
is of type int
it casts c
to an int
.
The line before string s; if (b) s = "blubb" + i; else s = "blubb" + c;
can be rewritten in a more readable way.
string s;
if(b)
{
s = "blubb" + i; // i is an int here
// So s = "blubb" + 1;
}
else
{
s = "blubb" + c; // c is a char here. The char 'A'.
// So s = "blubb" + 'A';
}
Two answer the second part of your question. (b ? c : i)
is resolving to an int
when you would expect to see a char
.
This is because converting a char
to an int
is an implicit conversion.
Where as converting an int
to a char
is a explicit conversion.
In the ternary operator the implicit conversion is used.
Upvotes: 2
Reputation: 28157
From MSDN:
condition ? first_expression : second_expression
...
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
As there is an explicit conversion between char
and int
(but only an explicit the other way around) the type of the following call
boolean ? integer : character
is int
.
When you concatenate any non-string object with a string, ToString()
is called on the object.
This means:
"string" + integer
= "string" + integer.ToString()
and
"string" + character
= "string" + character.ToString()
and finally
"string" + (boolean ? integer : character)
= "string" + integerResult
= "string" + integerResult.ToString()
Upvotes: 2