String.Format in C#

One of the painful things about good old ASP was string formatting, VBScript simply didn’t have anything useful. C# (and VB.Net) do, but MSDN doesn’t provide a quick reference to the formatting options.

To compare string formatting in C# to those in C lets have an example,

char szOutput[256];
sprintf(szOutput, “At loop position %d.\n”, i);

sprintf takes an output buffer, a format string and any number of arguments to substitute into the format string.

The C# equivalent for sprintf is String.Format, which takes a format string and the arguments. It returns a string, and because you’re not passing in a buffer there’s no chance of a buffer overflow.

string outputString = String.Format(“At loop position {0}.\n”, i);

Formatting strings
There’s not much formatting that can be applied to a string. Only the padding / alignment formatting options can be applied. These options are also available to every argument, regardless of type.

Example Output
String.Format(“–{0,10}–“, “Select”); — Select–
String.Format(“–{0,-10}–“, “Select “); –Select —


Back to top