C# AppendFormat

Letters of the alphabet: ABC

AppendFormat is available on StringBuilder. With it we append different kinds of data—including string literals—to an underlying string buffer. With it we create code that is clearer to read and modify. It handles formatting strings.

This C# example set uses the StringBuilder AppendFormat method.

Sentence example

Note

This first example demonstrates how you can use a string literal to generate sentences in your StringBuilder. You can put parenthesis around values, which would be more confusing syntactically if you were to use string concatenation. 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 without running the program.

String Concat Programs
Program that uses AppendFormat [C#]

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).

Int example

Int keyword

Here we look at the useful AppendFormat method on the StringBuilder type. Format strings in the C# language are a powerful of simplifying string changes for display. The AppendFormat method uses the same syntax. There are many advanced rules for string formatting, which are out of the scope of this document.

string.Format Method
Program that uses AppendFormat [C#]

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

Summary

The C# programming language

The StringBuilder AppendFormat method is very useful for generating text based on a pattern. The method receives a variable number of arguments. We saw how you can specify new lines in the AppendFormat method in both examples. For optimal code clarity, the AppendFormat method is ideal.

StringBuilder Secrets
.NET