3

I'm a beginner to C#. So far I came across several ways that I can use to embed variables in a string value. One of the is String Interpolation which was introduced in C# 6.0. Following code is an example for String Interpolation.

int number = 5;
string myString = $"The number is {number}";

What I want to know is whether there is a benefit of using String Interpolation over the following ways to format a string.

// first way
int number = 5;
string myString = "The number is " + number;

//second way
int number = 5;
string myString = string.Format("The number is {0}", number);
gayashanbc
  • 937
  • 1
  • 15
  • 30
  • @KQa - I would disagree. The OP knows how to do string interpolation, they are more concerned about what goes on under the bonnet whereas the question that you reference asks how to interpolate strings. – ridecar2 Apr 20 '17 at 05:38
  • The question this is marked as a duplicate of was specifically asking about performance of the two methods. This question is more broad, so I flagged to reopen.. – StayOnTarget Feb 21 '19 at 14:49

1 Answers1

4

The first way that you have shown will create multiple strings in memory. From memory I think it creates the number.ToString() string, the literal "The number is " string and then the string with name myString

For the second way that you show it's very simple: String interpolation compiles to the string.Format() method call that you use.

EDIT: The second way and the interpolation will also support format specifiers.

A more detailed discussion by Jon Skeet can be found here: http://freecontent.manning.com/interpolated-string-literals-in-c/

Community
  • 1
  • 1
ridecar2
  • 1,968
  • 16
  • 34
  • I think `string.Format` calls `ToString()` on the `int` as well: https://referencesource.microsoft.com/#mscorlib/system/text/stringbuilder.cs,1466 – Orphid Apr 20 '17 at 05:48
  • 1
    thank you for the explanation – gayashanbc Apr 20 '17 at 05:48
  • @Orphid - I agree with that, in fact I'm pretty sure that it must do. What it doesn't do is allow for formatting as I recall, should add that to my answer. – ridecar2 Apr 20 '17 at 05:50
  • @ridecar2 - I guess, the thing that interests me and might interest the OP is how the implementations differ. Given the need to `ToString` the arg anyway, does `string.Format` actually create fewer strings overall in memory and, if so, how does it do it? - StringBuilders, right? – Orphid Apr 20 '17 at 05:56
  • @Orphid - Now you're making me want to fire ILDASM up. I must resist the temptation! – ridecar2 Apr 20 '17 at 05:57