To Format Or Interpolate

In a devBetter discussion, a question was raised regarding composing strings: “Why would a developer use String.Format, when string interpolation seems much cleaner and easier to use?”

In case you are not familiar with StringFormat or string interpolation, here’s a code sample that demonstrates using them to compose a string:

Variables x, y, and z will all contain the same string value (“My name is Rick and my shoe size is 9.5”), but you can see how each approach used becomes progressively easier to read and understand. String interpolation is like a shorthand for a call to String.Format.

We’ll soon see that behind the scenes, string interpolation actually compiles down into a call to String.Format, but let’s look at String.Format, first.

String.Format evaluates its format parameter at runtime. Consider the following code that accepts a format string from the console, and displays the result of String.Format():

Here’s a sample of the console output:

Enter a format that contains {0} and {1}:
You entered: Name {0} Shoe {1}
Result: Name Rick Shoe 9
Enter a format that contains {0} and {1}:
You entered: Shoe {1} Name {0}
Result: Shoe 9 Name Rick

In contrast, interpolation builds the format expression at compile time.

Let’s see what happens when we try to use string interpolation like String.Format:

Why don’t we get the same results? The reason is that the compiler “hard codes” the interpolated format.

Let’s look at how the compiler compiles the following string interpolation:

Here is the IL generated by the compiler.

Compared to our “changeable” format in the while(true) loop, the format expression (the line starting with IL_000A) is “baked in”: the string “My name is …” will never change.

Both String.Format and string interpolation are valuable tools in our toolbelt. I use string interpolation most of the time (since it was added to C# in version 6), but String.Format can be very useful when you need to have configurable formats.