Multiline C# interpolated string literal

C#.NetStringMultilineString Interpolation

C# Problem Overview


C# 6 brings compiler support for interpolated string literals with syntax:

var person = new { Name = "Bob" };

string s = $"Hello, {person.Name}.";

This is great for short strings, but if you want to produce a longer string must it be specified on a single line?

With other kinds of strings you can:

    var multi1 = string.Format(@"Height: {0}
Width: {1}
Background: {2}",
        height,
        width,
        background);

Or:

var multi2 = string.Format(
    "Height: {1}{0}" +
    "Width: {2}{0}" +
    "Background: {3}",
    Environment.NewLine,
    height,
    width,
    background);

I can't find a way to achieve this with string interpolation without having it all one one line:

var multi3 = $"Height: {height}{Environment.NewLine}Width: {width}{Environment.NewLine}Background: {background}";

I realise that in this case you could use \r\n in place of Environment.NewLine (less portable), or pull it out to a local, but there will be cases where you can't reduce it below one line without losing semantic strength.

Is it simply the case that string interpolation should not be used for long strings?

Should we just string using StringBuilder for longer strings?

var multi4 = new StringBuilder()
    .AppendFormat("Width: {0}", width).AppendLine()
    .AppendFormat("Height: {0}", height).AppendLine()
    .AppendFormat("Background: {0}", background).AppendLine()
    .ToString();

Or is there something more elegant?

C# Solutions


Solution 1 - C#

You can combine $ and @ together to get a multiline interpolated string literal:

string s =
$@"Height: {height}
Width: {width}
Background: {background}";

Source: https://stackoverflow.com/questions/31764898/ (Thanks to @Ric for finding the thread!)

Solution 2 - C#

I'd probably use a combination

var builder = new StringBuilder()
    .AppendLine($"Width: {width}")
    .AppendLine($"Height: {height}")
    .AppendLine($"Background: {background}");

Solution 3 - C#

Personally, I just add another interpolated string using string concatenation

For example

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrew NoakesView Question on Stackoverflow
Solution 1 - C#Dmytro ShevchenkoView Answer on Stackoverflow
Solution 2 - C#saraView Answer on Stackoverflow
Solution 3 - C#Andrew MonteithView Answer on Stackoverflow