C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.ConcatC# program that uses AppendFormat
using System;
using System.Text;
class Program
{
static void Main()
{
StringBuilder builder = new StringBuilder();
string[] data = { "Dot", "Net", "Perls" };
int counter = 0;
foreach (string value in data)
{
builder.AppendFormat("You have visited {0} ({1}).\n",
value,
++counter);
}
Console.WriteLine(builder);
}
}
Output
You have visited Dot (1).
You have visited Net (2).
You have visited Perls (3).
Also: There are many advanced rules for string formatting, which are not covered in this document.
string.FormatC# program that uses AppendFormat with ints
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());
}
}
Output
int: 1.0
int: 4.0
int: 6.0
Note: For optimal code clarity, the AppendFormat method is ideal. It is not ideal for performance.