C#: Using StringBuilder for Concatnation


/ Published in: C#
Save to your folder(s)

StringBuilder class is a much better way to concatenate strings. Unlike a string object it can be changed as needed, and is much more efficient than using +=


Copy this code and paste it in your HTML
  1. // This example concatenates using StringBuilder object then writes contents of the
  2. // StringBuilder object out to a file using streamwriter
  3.  
  4. StringBuilder textSB = new StringBuilder();
  5. string newLine;
  6.  
  7. for(int i = 0; i < 50; i++)
  8. {
  9. newLine = "Line # " + i;
  10. textSB.Append(newLine).Append("|").Append("\r\n");
  11. }
  12.  
  13. string filePath = @"c:\output.txt";
  14. using (StreamWriter outFile = new StreamWriter(filePath))
  15. outFile.Write(textSB.ToString());

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.