Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Concatenating strings using StringBuilder in C#

When performance is important, you should always use the StringBuilder class to concatenate strings.
The following code uses the Append method of the StringBuilder class to concatenate strings without the chaining effect of the + operator.

  1. using System;
  2. using System.IO;
  3. using System.Text;
  4.  
  5. namespace forgetCode
  6. {
  7. class program1
  8. {
  9. static void Main(string[] args)
  10. {
  11. // Use StringBuilder for concatenation in tight loops.
  12. StringBuilder sb = new StringBuilder();
  13. for (int i = 0; i < 10; i++)
  14. {
  15. sb.AppendLine(i.ToString());
  16. }
  17. System.Console.WriteLine(sb.ToString());
  18.  
  19. // Keep the console window open in debug mode.
  20. System.Console.WriteLine("Press any key to exit.");
  21. System.Console.ReadKey();
  22.  
  23.  
  24. }
  25. }
  26. }


Output:
0
1
2
3
4
5
6
7
8
9

..