Home
Map
VB.NET
StringBuilder Append and AppendLine
This page was last reviewed on Dec 7, 2023.
Dot Net Perls
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.
StringBuilder
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.
For
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 Module
BUILDER: 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.
Environment.NewLine
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 Module
One 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 7, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.