What's the best way to create multi-line string in C#?
I know the following methods:
var result = new StringBuilder().AppendLine("one").AppenLine("two").ToString()
looks too verbose.
var result = @"one
two"
looks ugly and badly formatted.
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.
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.
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.
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"
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With