Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best syntax to create multi-line string

What's the best way to create multi-line string in C#?

I know the following methods:

Using StringBuilder

var result = new StringBuilder().AppendLine("one").AppenLine("two").ToString()

looks too verbose.

Using @

      var result = @"one
two"

looks ugly and badly formatted.

Do you know better ways?

like image 924
Konstantin Spirin Avatar asked Oct 02 '09 07:10

Konstantin Spirin


People also ask

How do you make a multiline string?

Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.

What are the different ways to declare multiline string?

Using triple quotes to create a multiline string. Using brackets to define a multiline String. Using backslash to entitle a multiline String. Using a join() method to define a multiline String.

How do you write multi line strings in template literals?

HTML. Example 2: If you use double/single quote to write multiline string then we use the newline character (\n). Use an extra backslash ( \ ) after every newline character (\n), this backslash tells the JavaScript engine that the string is not over yet.


1 Answers

What about this:

var result = string.Join(Environment.NewLine, new string[]{ 
    "one",
    "two" 
});

It's a bit painful and possibly an overkill, but it gives the possibility to preserve the lines separation in your code.
To improve things a little, you could use an helper method:

static string MultiLine(params string[] args) {
    return string.Join(Environment.NewLine, args);
}

static void Main(string[] args) {
    var result = MultiLine( 
        "one",
        "two" 
    );
}
like image 182
Paolo Tedesco Avatar answered Sep 29 '22 05:09

Paolo Tedesco