C# allows implicit conversions of integers to strings when used in an expression. For example, this is completely valid:
int myInt = 10;
string concatenatedString = "myInt is " + myInt;
string interpolatedString = $"myInt is {myInt}";
However, when the int is not being concatenated or interpolated, C# requires an explicit conversion.
int myInt = 10;
string myString = myInt;
// compiler error "Cannot implicitly convert type 'int' to 'string'"
Obviously this isn't a major pain: a simple .ToString()
takes care of this just fine. But if .NET knows that every possible int is also a valid string, why does it still require an explicit conversion? I'd like to know what's going on in the "mind" of the compiler.
object
s have aToString
method and treats theint
like anobject
. Just assigning anint
(or any otherobject
) to a string should be possible (by callingToString
), which seems like most of the time would be an error. If the compiler allowed anyobject
to be assigned to a string, would you want aMyClass
object to implicitly convert to a string without an error or warning? I wouldn't. – Becuzz Oct 12 '16 at 12:24int
specifically; what is special to you aboutint
? You can add any expression that has a type convertible toobject
to a string. So either your question really should be "why can't C# convertobject
tostring
?" or you should say why you think thatint
is more deserving of this conversion than, say,decimal
orIComparable<BigInteger>
orSystem.Delegate
. – Eric Lippert Oct 14 '16 at 16:01$"{myInt}"
(I'm told to add way more than 15 chars) – rwong Oct 17 '16 at 8:10