For example, the following code:
int n=1;
string str=$"{n}";
But after adding ToString()
explicitly, boxing will not happen.
int n=1;
//The compiler will recommend removing the explicit call of the ToString() method
string str=$"{n.ToString()}";
The book CLR via C#
writes that String.Format
will call the ToString
method internally to get the string representation of the object.
Since the ToString method is called internally, why does the boxing occur in Example 1?
"Calling ToString
" is not a magic way to prevent boxing. Boxing still happens if you called ToString
after it has been boxed, which is the case with string interpolation.
As you know, string interpolations generally desugars to string.Format
calls. If you look at the list of overloads available, you'll see that there isn't an overload that takes a value type like int
or long
. Every overload takes an object
. To pass an int
into these methods, it first needs to be boxed. string.Format
then calls ToString
at some point on the boxed object
.
Compare this to directly calling ToString
in the string interpolation. There is no conversion to a reference type (object
), so no boxing.