#14 – Composite Format Strings in C#

When working with C#, you’ll often want to create a string that is composed of some combination of static text and substituted variable values.  You do this by specifying a format string that contains a list of placeholders (format items) where the variable values will be substituted.  You also specify the actual values of the variables to be substituted.

Below is an example.  Here we substitute both string and integer variables.  The format items within the format string are indicated with a zero-based index surrounded by curly braces.  The index indicates which object in the list should be substituted.

    string name = "Sean";
    int age = 46;
    string sFinal = string.Format("{0} is {1} yrs old. {0} is old.", name, age);

This results in the string: Sean is 46 yrs old. Sean is old.

See also: Composite Formatting topic in MSDN.