For years we have all used string.Format, it was one of those constructs that I thought “oh wow”, when I first started using the .Net Framework back in 2004. One of my colleagues at the time remarked “Its sweet, isn’t it?”, I guess we were easily amused back then? In C# 6 we saw the introduction of string interpolation.
So going back to string.format, this line of code is an example of what we would have used:
var name = "fido";
var message = string.Format("My dog's name is {0}", name);
Console.WriteLine(message);
So in the example above, this would output “My dog’s name is fido”.
Now looking at an example with string interpolation we can do this:
var name = "fido";
var message = $"My dog's name is {name}";
Console.WriteLine(message);
This would also output the same of the previous piece of code, but it looks much more compact. In the example above, notice the special $ character. This character identifies the string as an interpolated string. This allows you to embed expression values into a literal string.
You may then wonder, aha, I can do this:
var string name = "fido";
var message = "My dog's name is {name}";
Console.WriteLine($message);
But this code above won’t compile. You cannot parameterise the format string.
Function calls
You can call a function from within an interpolated string, look at the following code below:
Console.WriteLine($"{DateTime.UtcNow.ToString("dd-MM-yyyy HH:mm:ss")}");
But you probably wouldn’t want to do that in this case, you would probably do this instead:
Console.WriteLine($"{DateTime.UtcNow: dd-MM-yyyy HH:mm:ss}");
The above code is the formatting expression syntax, its much more compact than the previous example.
So what happens at the compiler level?
The compiler generates a string.Format in the IL for string interpolation, so this feature is more syntactic sugar. The string literal has to be static, you could not define dynamically. Unlike string.Format, where you can specify a format string at runtime.
Conclusion
I think the string interpolation syntax is much more readable than the old string.Format syntax.
You don’t have to worry about the parameter ordering like you did with string.Format or missing out a parameter in the format string parameter by accident.
You will probably save yourself some typing using this syntax.
If you want to know more please delve into the documentation.
Watch Out For
You have to remember to add the $ special character at the beginning of the string, otherwise you would introduce an unintentional bug. That would not be cool!