There is code 1

int i = 123; string s = $"{i}"; 

And there is code 2

 int i = 123; string s = $"{i.ToString()}"; 

In the first variant, boxing will occur or doesn’t it happen with interpolation and the compiler understands what to call ToString ?

  • one
    Vohіng is a replacement for a specific function Namely string.Format. Open MSDN and read msdn.microsoft.com/ru-ru/library/… . Those. $ "{i}" is an exclusive string.Format ("{0}", i) and so on. - nick_n_a
  • 3
    Boxing will occur because string.Format expects an array at the input, the elements of which are of type object . i will be cast to object , and since this is a significant type, it must be packaged. In the second case, boxing does not occur, since string is already a reference type. - Mark Shevchenko
  • Another theme of the $ -cub codingblocks.net/podcast/episode2 - nick_n_a
  • VohŃ–ng - I messed up, this is not a replacement. $ - is replaced by string.Format - and immediately the answer to the question becomes obvious. - nick_n_a
  • one
    @nick_n_a does not become. The question is: "Is a smart compiler enough to insert ToString ()"? And as far as I know, not enough. And also the resharper puts his poles in the wheels - vitidev

2 answers 2

one)

 string s = $"{i}"; 

turns into string.format, which accepts objects, boxing is present

boxing

2)

 string s = $"{i.ToString()}"; 

string is transmitted, nothing to box

no boxing

  • It would be necessary to benchmark, all of a sudden inside int.ToString () is the same boxing :) - Andrey NOP
  • @AndreyNOP, there is rather a challenge for the native function - Grundy
  • 2
    @AndreyNOP and this function is called in both variants - Pavel Mayorov
  • 2
    @ AndreiNOP hold the benchmark habr.com/post/70217 - vitidev
  • one
    @vitidev, yes I already drove myself: pastebin.com/1AVF6DQy - Andrey NOP

In the first version boxing will occur.

Yes.

with interpolation this does not happen and the compiler understands what to call ToString ?

Your statement “you must call ToString ” is not correct, because you must “call” not the same ToString that you call.

 using System; class Test { struct S: IFormattable { public override string ToString() => "Object.ToString"; public string ToString(string format, IFormatProvider formatProvider) => "IFormattable.ToString"; } public static void Main() { S s = new S(); Console.WriteLine($"{s}"); Console.WriteLine($"{s.ToString()}"); } } 

https://ideone.com/gRz74U

Since the behavior of String.Format not part of the standard of the C # language, the compiler does not have the right to perform the optimization proposed by you, since it cannot know which ToString needs to be called and with what parameters.

Moreover, if the S type definition is in a different assembly, then at compile time the compiler will not even have enough information to determine which method to call.