C# StringBuilder AppendFormatUse the AppendFormat method to append complex data to a StringBuilder.
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.
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.
using System; using System.Text; class Program { static void Main() { 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.
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.
© 2007-2022 sam allen.
see site info on the changelog.