Why can boxed integer value get implicitly converted to string type?
I thought class can be implicitly converted only to:
- any class in the chain from whi开发者_如何学运维ch it is derived
- any interface that it implements
a) None of the above is true in next example, so why does boxed integer value get implicitly converted to string
type:
string s = 100 + “question”;
b) Why then doesn’t the value in next assignment also get implicitly converted to string
type:
string s = 100;
thanx
That's just the string concatenation operator - nothing to do with boxing or integers in particular... it's any value which is being concatenated with a string.
Your second example doesn't involve any concatenation, hence no conversion.
From the C# spec, section 7.8.4:
For an operation of the form x + y, binary operator overload resolution (§7.3.4) is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.
The predefined addition operators are listed below. For numeric and enumeration types, the predefined addition operators compute the sum of the two operands. When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.
and then:
String concatenation:
string operator +(string x, string y); string operator +(string x, object y); string operator +(object x, string y);
These overloads of the binary + operator perform string concatenation. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If
ToString
returns null, an empty string is substituted.
In fact, in your example, with the current MS C# compiler, it will simply box the integer and call string.Concat(object, object)
- but the compiler knows that will have the same result as calling string.Concat(100.ToString(), "question")
.
One interesting point of fact: the + operator doesn't exist in the string
class itself. The language has special handling for it (as we've already seen) which ends up calling Concat
. One advantage of this is that
x + y + z
can be compiled into
string.Concat(x, y, z)
which can perform the whole concatenation in one go, rather than building a pointless intermediate string.
(Also, note that the compiler performs concatenations of compile-time constant strings itself.)
This is a feature of the + operator and not the boxing.
This has to do with the +
operator.
Essentially, the method signature for +
in this case is:
public string +(string s) {
return this.ToString() + s;
}
So, the int
gets converted to a string
.
But, it is simply a syntax error to try and stick an int
value into a string
reference.
精彩评论