Multiline C# interpolated string literal

54,995

Solution 1

You can combine $ and @ 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!)

Solution 2

I'd probably use a combination

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

Solution 3

Personally, I just add another interpolated string using string concatenation

For example

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

I find that is easier to format and read.

This will have additional overhead compared to using $@" " but only in the most performance critical applications will this be noticeable. In memory string operations are extremely cheap compared to data I/O. Reading a single variable from the db will take hundreds of times longer in most cases.

Share:
54,995
Drew Noakes
Author by

Drew Noakes

Developer on .NET at Microsoft.

Updated on October 18, 2020

Comments

  • Drew Noakes
    Drew Noakes over 3 years

    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?