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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #14 – Composite Format Strings in C#

  1. Pingback: #17 – Methods that Support Composite Formatting « 2,000 Things You Should Know About C#

  2. Pingback: #973 – Format Items in Composite Format Strings Can Be in Any Order | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: