Search code examples
c#.netstringmultilinestring-interpolation

Multiline C# interpolated string literal


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?


Solution

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

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

    Source: Long string interpolation lines in C#6 (Thanks to @Ric for finding the thread!)