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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.