16.12 Append and AppendFormat Methods of Class StringBuilder
Class StringBuilder provides overloaded Append methods that allow various types of values to be added to the end of a StringBuilder. The Framework Class Library provides versions for each simple type and for character arrays, strings and objects. (Remember that method ToString produces a string representation of any object.) Each method takes an argument, converts it to a string and appends it to the StringBuilder. Figure 16.11 uses several Append methods (lines 22–40) to attach the variables’ string representations in lines 10–18 to the end of the StringBuilder.
Class StringBuilder also provides method AppendFormat, which converts a string to a specified format, then appends it to the StringBuilder. The example in Fig. 16.12 demonstrates AppendFormat.
Line 13 declares a format string that consists of text and format items. Each format item in braces ({}) is a placeholder for a value. Format items also may include the same optional formatting you’ve seen throughout this book in interpolated strings. Line 16 declares and initializes an array of objects that will be formatted. Line 19 shows a version of AppendFormat that takes two parameters—a format string and an array of objects to serve as the arguments to the format string. The object at index 0 of the array is formatted by the format item "{0}", which simply produces the object’s string representation. The object at index 1 of the array is formatted by the format item "{1:C}", which formats the object as currency.
Lines 22–24 declare another format string with three format specifiers:
The first—{0:d3}—formats a three-digit integer value. Any number having fewer than three digits will have leading zeros.
The second—{0,4}—formats a string in a right-aligned field of four characters.
The third—{0,-4}—formats a string in a left-aligned field of four characters.
Line 27 uses a version of AppendFormat that takes two parameters—a format string and an object to format. In this case, the object is the number 5, which is formatted by all three format specifiers. The output displays the result of applying these two versions of Append-Format with their respective arguments.