C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Version 1: In this version of the code we call Append() on the reference to the StringBuilder repeatedly.
Version 2: Here we combine multiple Append calls into a single statement. Append() returns a reference to the StringBuilder.
C# program that uses Append syntax
using System;
using System.Text;
class Program
{
static void Main()
{
const string s = "(s)";
// Version 1: call Append repeatedly.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 3; i++)
{
builder.Append("Start");
builder.Append(s);
builder.Append("End");
}
// Version 2: use fluent interface for StringBuilder.
StringBuilder builder2 = new StringBuilder();
for (int i = 0; i < 3; i++)
{
builder2.Append("Start").Append( s).Append("End");
}
Console.WriteLine("BUILDER: {0}", builder);
Console.WriteLine("BUILDER 2: {0}", builder2);
}
}
Output
BUILDER: Start(s)EndStart(s)EndStart(s)End
BUILDER 2: Start(s)EndStart(s)EndStart(s)End
Arguments: AppendLine is called with 0 or 1 arguments. When you call AppendLine with no arguments, it just appends the newline sequence.
String: With a string argument, it appends that string and the newline sequence. There is no way to use a format string with AppendLine.
AppendFormatC# program that uses AppendLine
using System;
using System.Text;
class Program
{
static void Main()
{
// Use AppendLine.
StringBuilder builder = new StringBuilder();
builder.AppendLine("One");
builder.AppendLine();
builder.AppendLine("Two").AppendLine("Three");
// Display.
Console.Write(builder);
// AppendLine uses \r\n sequences.
Console.WriteLine(builder.ToString().Contains("\r\n"));
}
}
Output
One
Two
Three
True
Tip: This means every line in your text output will be one character shorter. In ASCII format, this will save one byte per line.
And: Your C# program will save 2 bytes per line in its memory, because a character is 2 bytes long.
Char