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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #14 – Composite Format Strings in C#

  1. Pingback: #17 – Methods that Support Composite Formatting « 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 )

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers