Best syntax for creating a multi-line string

What is the best way to create a 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 poorly formatted.

Do you know the best ways?

+7
string syntax c # multiline
source share
8 answers

How about this:

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

This is a little painful and possibly overkill, but it makes it possible to keep the line separation in your code. To improve the situation a bit, you can use a helper method:

 static string MultiLine(params string[] args) { return string.Join(Environment.NewLine, args); } static void Main(string[] args) { var result = MultiLine( "one", "two" ); } 
+20
source share

How about this?

 var result = "one\ntwo"; 

If you are worried about the ends of a particular OS, use Format :

 var result = String.Format("one{0}two", Environment.NewLine); 

(Well, "fussy" is not the right word: when working with text files, working with outdated software often requires or even requires bindings to specific OSs).

+10
source share

The "best" is a very open point.

You after:

  • Code execution
  • Coding rate can be recorded
  • An opportunity for another coder to easily understand this.
  • The ability for another encoder to easily modify it.

They all contribute a lot to the β€œbest” way to do something.

+3
source share

I would say it depends on what you need ...

But to simplify this, I would go:

 var s = new StringBuilder(); s.Append("one"); s.Append("two"); s.ToString(); 

But since we do not know why you need it. It’s hard to give the best clues.

+2
source share

You should not define large lines in source code. You must define it in an external text file:

 string s = File.OpenText("myfile.txt").ReadToEnd(); 
+1
source share

By undoing what @codymanix said , you can place a long multi-line line in the resource file. This may be easier for some deployment scenarios, as the text β€œfile” will be included in your DLL / EXE.

+1
source share

Ehm, how about:

 string s = "abc\n" + "def\n" ; 
+1
source share

Sometimes you need more than one line. I use Environment.NewLine, but I put it in a method to multiply it. :)

  private string newLines(int multiplier) { StringBuilder newlines = new StringBuilder(); for (int i = 0; i < multiplier; i++) newlines.Append(Environment.NewLine); return newlines.ToString(); } 
0
source share

All Articles