Home
C#
StringBuilder AppendFormat
This page was last reviewed on Oct 3, 2023.
Dot Net Perls
AppendFormat. This C# method is available on StringBuilder. It handles formatting strings. With it we append different kinds of data—including string literals—to an underlying string buffer.
With AppendFormat, we can write code that is clearer to read and modify. Fewer method calls are needed—more complex formatting can be done in single invocation.
StringBuilder
This first example uses a string literal to generate sentences in a StringBuilder. We can put characters (like parentheses) around values.
Tip The core reason to use AppendFormat here is for clarity of the resulting code. It is clear to see what string data will be generated.
string.Concat
using System; using System.Text; StringBuilder builder = new StringBuilder(); string value = "ABC"; int number = 1; // Combine the 2 values with AppendFormat. builder.AppendFormat("R: {0} ({1}).", value, number); Console.WriteLine(builder);
R: ABC (1).
Int example. To continue, we can format integers with AppendFormat using standard format strings. Here we control the number of places after the decimal.
Tip It would be better to use more descriptive variable names here, but the example works correctly.
string.Format
using System; using System.Text; class Program { static int[] _v = new int[] { 1, 4, 6 }; static void Main() { StringBuilder b = new StringBuilder(); foreach (int v in _v) { b.AppendFormat("int: {0:0.0}{1}", v, Environment.NewLine); } Console.WriteLine(b.ToString()); } }
int: 1.0 int: 4.0 int: 6.0
Summary. The StringBuilder AppendFormat method is useful for generating text based on a pattern. The method receives a variable number of arguments.
A final note. For optimal code clarity, the AppendFormat method is ideal. Usually it is not ideal for performance, but this performance often is not the primary issue.
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 Oct 3, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.