Line breaks in string interpolation

Line breaks allowed in interpolation expressions with C#11

Home DailyDrop

Daily Knowledge Drop

Coming with C#11 (.NET7), line breaks will now be allowed in the interpolation expressions in interpolated strings.


Prior to C#11

Let's look at a simple example:

var aCollectionOfStringValues = new string[]
{
    "String1",
    "String2",
    "String3"
};

// Before C#11
Console.WriteLine($"The first letter of the 2nd item is {aCollectionOfStringValues[1].ToLower().First()}");

The interpolation expression of aCollectionOfStringValues[1].ToLower().First() is fairly long however, unlike normal code, it cannot be split across different lines.


C#11

C#11 introduced the ability to do the following:

var aCollectionOfStringValues = new string[]
{
    "String1",
    "String2",
    "String3"
};

// With C#11
Console.WriteLine($"The first letter of the 2nd item is {
    aCollectionOfStringValues[1]
    .ToLower()
    .First()}");

The interpolation expression can now contain line breaks and be split across lines, making the code easier to read.


Notes

A very small change being introduced with C#11, but one which will add to the quality of life as a developer, removing to need to excessive horizontal scrolling, and making code easier to read.


References

C# 11 - New Features in .NET 7

Daily Drop 57: 21-04-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net C#11 .net7 interpolation linebreak