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);
2
  • @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. Commented Apr 20, 2017 at 5: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.. Commented Feb 21, 2019 at 14:49

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

5 Comments

I think string.Format calls ToString() on the int as well: referencesource.microsoft.com/#mscorlib/system/text/…
thank you for the explanation
@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 - 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 - Now you're making me want to fire ILDASM up. I must resist the temptation!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.