C#11 Features - Newlines In String Interpolations

The string Interpolation feature was introduced in C# 6 and this is a replacement for String.Format() method. In Format() we use to keep placeholders with sequence numbers and we need to pass the value from the second parameter in the same sequence as below to replace it in the given expression.

int csharpVersion = 6; 
int dotNETVersion = 7; 
String.Format("This article is all about C#{0} and .NET {1}", csharpVersion , dotNETVersion );

With this approach, we cannot know if the passed parameters match the placeholders in the given string at compile time which leads to runtime errors if the parameter counts mismatches. String Interpolation is the new feature where it allows to provide the actual variable to be part of the string with open and end curly braces '{}' and this string should prefix with the '$' symbol as below.

int csharpVersion = 6; 
int dotNETVersion = 7; 
var s = $"This article is all about C#{csharpVersion} and .NET {dotNETVersion}";

As observed earlier we use to pass the placeholder values as a parameter and using the string interpolation feature it is more readable and does not need to worry about matching the placeholder sequence and the parameters.

Everything looks awesome till here and this feature is really a game changer. But, there are some drawbacks identified when we want to use lengthy expressions or formulas. In such cases, we need to strictly write the complete expression in a single line as follows.

var s = $"My future car name is {list.Where(car => car.StartsWith("T")).Select(car => car[0]).FirstOrDefault()}";

Above we used the LINQ expression to get the car name. As we are using LINQ expression we have the freedom to make it a multiline statement as below 

list.Where(car => car.StartsWith("T")) 
    .Select(car => car[0]) 
    .FirstOrDefault();

But, we cannot inject this into the string interpolation due to multiline restrictions. Now, in C# 11 these restrictions got removed and now string interpolation supports multiline expressions too. The statement can be written as below and is valid from C# 11. 

var s = $"My future car name is {list.Where(car => car.StartsWith("T")) 
    .Select(car => car[0]) 
    .FirstOrDefault() 
}";

This is all about the new improvisations for the existing string interpolation feature from C# 11. 

Happy Coding ðŸ˜Š 


Similar Articles