If you've been dabbling in C# for a while, you've probably come across the term "String interpolation." It's one of those features that has made our coding lives a bit more colorful.
In this tutorial , let's dive deep and see how this gem has evolved over the years., exploring its origins, its evolution, and the latest enhancements.
Where it all Began: Origins of String Interpolation
String interpolation was introduced in C# 6 as a more readable and concise way to format strings.
Back in the C# 6 era, string interpolation made its grand entrance. Before this, we were stuck with string.Format
, juggling placeholders and hoping we didn't mix them up.
Remember doing this?
string carModel = "Sedan";
string carBrand = "Maruti";
string carYear = "2020";
string formattedString = string.Format("The car model is: {0}, brand is: {1}, and it was manufactured in {2}", carModel, carBrand, carYear);
Here, we’re using the string.Format
method to format our string. The {0}
, {1}
, and {2}
were used as placeholders that got replaced by the values of carModel
, carBrand
, and carYear
respectively.
The disadvantage of this approach was as the number of variables increases, it became harder to track which placeholder corresponded to which variable, thereby making the code less readable.
But with string interpolation, it felt like a breath of fresh air:
string carModel = "Sedan";
string carBrand = "Maruti";
string carYear = "2020";
string formattedString = $"The car model is: {carModel}, brand is: {carBrand}, and it was manufactured in {carYear}";
No more counting placeholders, right?
With interpolated strings, we can now directly embed the variables inside the string. 0
The way it works is that the $
before the string indicates that it’s an interpolated string. Thus the code now is more readable, plus there’s no need to match placeholders with variables, which reduces the chance of errors.
The Journey: Evolution of String Interpolation from C# 6 to C# 12
C# 6: Introduction of String Interpolation
This was the dawn of string interpolation. Simple and elegant.
Example:
string carBrand = "Maruti";
string message = $"The car brand is {carBrand}";
C# 7 & 8: Refinements and Usability
While C# 7 and 8 didn’t introduce major changes to string interpolation, it fine-tuned the feature, ensuring it meshed well with other language aspects.
Example: Using interpolated strings with local functions:
string GetCarDetails(string brand, int year)
{
return $"The car brand is {brand} and it was manufactured in {year}.";
}
string details = GetCarDetails("Maruti", 2020);
This approach was more intuitive than using placeholders, especially when dealing with multiple variables.
C# 9: Performance Improvements
C# 9 brought about performance enhancements to string interpolation, particularly beneficial when constructing large strings or in performance-critical applications.
Example:
Building a large string using string interpolation:
List<string> carBrands = new List<string> { "Ambassador", "Maruti", "Tata", "Mahindra" };
StringBuilder sb = new StringBuilder();
foreach (var brand in carBrands)
{
sb.AppendLine($"Brand: {brand}, Founded in: {GetFoundationYear(brand)}");
}
string carHistory = sb.ToString();
int GetFoundationYear(string brand)
{
// Sample logic to return a foundation year based on the brand
return brand switch
{
"Ambassador" => 1948,
"Maruti" => 1983,
"Tata" => 1991,
"Mahindra" => 1954,
_ => 0,
};
}
In this example for C# 9, we're emphasizing the use of string interpolation in a loop to build a larger string, showcasing the performance improvements in constructing strings using interpolation.
C# 10: Improved Interpolated Strings
This version was a game-changer. From directly embedding variables to conditional interpolation and format specifiers, it brought a lot to the table.
1. Interpolated String Handlers:
Before:
string name = "Supro";
string age = "44";
string city = "Cloud9";
var message = string.Format("Hello {0}, aged {1}, from {2}!", name, age, city);
Here, we’re using the string.Format
method to format our string. The {0}
, {1}
, and {2}
are placeholders that get replaced by the values of name
, age
, and city
respectively. As the number of variables increases, it becomes cumbersome to manage and prone to errors.
After:
string name = "Supro";
string age = "44";
string city = "Cloud9";
FormattableString message = $"Hello {name}, aged {age}, from {city}!";
With interpolated strings, we can now directly embed the variables inside the string. This makes the code more concise and reduces the chance of mismatching placeholders.
2. Conditional Interpolation:
Before:
bool isMorning = true;
string greeting = isMorning ? "Good morning" : "Good evening";
string name = "Bob";
var message = string.Format("Hello {0}, {1}!", name, greeting);
Earlier we were using a combination of ternary conditional operator and string.Format
to construct our message. As you can see, this can become hard to read with complex conditions and multiple variables.
After:
bool isMorning = true;
string name = "Bob";
var message = $"Hello {name}, {(isMorning ? "Good morning" : null)}!";
In this improved version, we can now conditionally include parts of the interpolated string directly. The code as you can see is more readable allowing for more flexible string construction.
3. Format Specifiers:
Before:
double cost = 100.50;
double tax = 10.05;
var price = string.Format("Total price: {0:C2}", cost + tax);
Here, we’re using string.Format
to format the sum of cost
and tax
as a currency with two decimal places.
This approach requires us to keep track of the format specifiers and their corresponding variables.
After:
double cost = 100.50;
double tax = 10.05;
var price = $"Total price: {cost + tax:C2}";
With the improved interpolated strings, we can directly apply the format specifier :C2
inside the interpolated string, making the code more intuitive and reducing the chance of format specifier mismatches.
C# 11: Raw String Literals and New Line in Interpolation
Raw String Literals:
Before:
var path = "C:\\Users\\John\\Documents";
Backslashes in strings need to be escaped with another backslash, making paths and regular expressions cumbersome.
After:
var path = @"C:\Users\John\Documents";
Raw string literals, introduced in C# 11, allow us to write strings without needing to escape special characters using the @
symbol before the string.
New Line in Interpolation:
Before:
string name = "Alice";
var message = $"Hello\n{name}!";
To include a new line in a string, we had to use the \n
escape sequence.
After:
string name = "Alice";
var message = $"Hello
{name}!";
As you can see, C# 11 now allows us to directly include new lines in interpolated strings. This makes the code more readable.
Advantages of String Interpolation
Interpolated strings are more readable as they allow the developer to see the final string structure directly, with embedded expressions.
They also reduce the need for additional placeholders and function calls.
String Interpolation also supports any expression type, including method calls and arithmetic operations.
Conclusion
From its introduction in C# 6 to the latest enhancements in C# 11 and anticipated features in C# 12, string interpolation has proven to be an invaluable feature in C#.
It has not only made string formatting more readable and concise but has also evolved to address performance concerns and provide more flexibility to developers.
As C# continues to evolve, string interpolation is bound to see even more improvements, solidifying its place as one of the most beloved features of the language.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn