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.
Best Answer
In both cases, the language is offering syntactic sugar features, rather than doing implicit casting:
is converted to the
string Concat(object, object)
method during compilation:And in the second case,
is converted to
string Format(string, object)
(or equivalent) method during compilation:So in both cases, the
int
is being boxed to anobject
and each method then calls.ToString()
on that object. No implicit casting is required.As for the question in your title: "Why can't C# implicitly convert int to string?", the answer to that, is that neither the
String
class, not theInt32
struct implement theimplicit operator
, so implicit conversions aren't possible between those types. You might be interested to know though that post C# 7, one feature being considered for the language is called "Extension everything". This would allow you to add implicit conversions between various types and strings to the language, such that you could do something like:if you really wanted to. Of course, that raises the question, would you want to?