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.
This first example uses a string
literal to generate sentences in a StringBuilder
. We can put characters (like parentheses) around values.
AppendFormat
here is for clarity of the resulting code. It is clear to see what string
data will be generated.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
exampleTo continue, we can format integers with AppendFormat
using standard format strings. Here we control the number of places after the decimal.
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
The StringBuilder
AppendFormat
method is useful for generating text based on a pattern. The method receives a variable number of arguments.
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.