Append
, AppendLine
To add string
data to a StringBuilder
in VB.NET programs, we call the Append
or AppendLine
functions. These functions can be used in a single statement, or chained together.
With Append
, no extra characters are added after the argument. But AppendLine
adds a newline sequence, which is platform-dependent, and makes using StringBuilder
more convenient.
Append
exampleUsually when using StringBuilder
, we call Append
in a loop—here we have 2 For
-loops. We call Append
3 times in each loop.
Append
3 times in the body of the For
-loop, and each call to Append
occurs on its own line.Append
, so that we have only one line of code in the For
-loop here. The result is the same as the previous loop.Imports System.Text Module Module1 Sub Main() Const s As String = "(s)" ' Version 1: call Append in loop. Dim builder = New StringBuilder() For i = 0 To 2 builder.Append("Start") builder.Append(s) builder.Append("End") Next ' Version 2: call Append in loop in same statement. Dim builder2 = New StringBuilder() For i = 0 To 2 builder2.Append("Start").Append( s).Append("End") Next Console.WriteLine("BUILDER: {0}", builder) Console.WriteLine("BUILDER 2: {0}", builder2) End Sub End ModuleBUILDER: Start(s)EndStart(s)EndStart(s)End BUILDER 2: Start(s)EndStart(s)EndStart(s)End
AppendLine
exampleWhen we call AppendLine
, a newline sequence is added automatically at the end of every call. This is equal to the current platform's NewLine
property.
AppendLine
, only a newline sequence is appended.Imports System.Text Module Module1 Sub Main() ' Use AppendLine. Dim builder = New StringBuilder() builder.AppendLine("One") builder.AppendLine() builder.AppendLine("Two").AppendLine("Three") Console.Write(builder) End Sub End ModuleOne Two Three
Along with ToString
, the Append
and AppendLine
functions are the most commonly-used ones on StringBuilder
. AppendLine
has the extra convenience of a newline sequence on each call.