Append
, AppendLine
Append
adds data to a StringBuilder
in C# code. Append
method calls can be chained—this makes code more succinct and easier to read.
With AppendLine
, .NET places a newline sequence at the end of the specified string
. This method makes code easier to read as well.
Append
exampleRemember that StringBuilder
often improves your application's performance. But excessive method calls, on separate lines, can be hard to read.
Append()
on the reference to the StringBuilder
repeatedly.Append
calls into a single statement. Append()
returns a reference to the StringBuilder
.using System; using System.Text; 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);BUILDER: Start(s)EndStart(s)EndStart(s)End BUILDER 2: Start(s)EndStart(s)EndStart(s)End
AppendLine
exampleAppendLine
adds strings with a newline. With AppendLine
, a newline sequence is automatically inserted after the argument is added to the StringBuilder
buffer.
AppendLine
is called with 0 or 1 arguments. When you call AppendLine
with no arguments, it just appends the newline sequence.string
argument, it appends that string
and the newline sequence. There is no way to use a format string
with AppendLine
.using System; using System.Text; // 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"));One Two Three True
The newline sequence used in AppendLine
is equal to "\r\n" which is also available by referencing Environment.NewLine
.
There are 2 ways to specify newlines: the character "\n" alone, and the sequence "\r\n". AppendLine
always uses the sequence "\r\n". To save bytes, you can manually use "\n".
byte
per line.We can chain StringBuilder
Appends in cases where we call the method multiple times. We looked at the AppendLine
method and its overloads on the StringBuilder
type.