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 example. Usually when using StringBuilder, we call Append in a loop—here we have 2 For-loops. We call Append 3 times in each loop.
Version 1 We call Append 3 times in the body of the For-loop, and each call to Append occurs on its own line.
Version 2 We chain calls to 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 example. When 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.
Info When no arguments are passed to 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.