C# – Why Can’t C# Implicitly Convert int to string?

ccompilertype conversion

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:

var s = "1" + 1;

is converted to the string Concat(object, object) method during compilation:

var s = String.Concat("1", 1);

And in the second case,

var i = 1;
var s = $"1={i}";

is converted to string Format(string, object) (or equivalent) method during compilation:

var s = string.Format("1={0}", i);

So in both cases, the int is being boxed to an object 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 the Int32 struct implement the implicit 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:

string s = 1;

if you really wanted to. Of course, that raises the question, would you want to?

Related Topic