# Composite Formatting

Do you know the answer of Console.Write() Exercise 2 and Console.WriteLine() Exercise 3?

Console.Write("My name is ", "Talha");
1

When you want to write more than one values or objects in a single Console.Write method, then you have to use composite formatting. Composite formatting combines the values and objects into one string.

Run this program.

using System;

class MainClass
{
  public static void Main ()
  {
      Console.Write("My name is {0}", "Talha");
      Console.WriteLine("{0} {1}", "Hello", "Talha!");
  }
}
1
2
3
4
5
6
7
8
9
10

What is the output?

# Explanation

When you write Console.Write("My name is {0}", "Talha");

  1. Console.Write is the function
  2. What is inside () is the arguments to the function

In this case,

  1. the first argument "My name is {0}" is a format string
  2. {0} is the first format item
  3. "Talha" is the first value

Compiler will replace {0} with Talha.

Let's study the line 2.

When you write Console.WriteLine("{0} {1}", "Hello", "Talha!");

  1. Console.WriteLine is the function
  2. What is inside () is the arguments to the function

In this case,

  1. the first argument "{0} {1}" is a format string
  2. {0} is the first format item
  3. {1} is the second format item
  4. "Hello" is the first value
  5. "Talha!" is the second value

Compiler will replace {0} with Hello, and {1} with Talha!.

Notice that first format item has index 0 and it refers to the first value. Second format item has the index 1, and it refers to the second value. Can you guess which index is used to refer the third value?

You can have any number of values and format items. You only have to make sure you do not use an index that does not exist.

// incorrect code
Console.WriteLine("{0} {1} {2}", "Hello", "Talha!");
1
2

The above code will not compile because {2} refers to a third value which is not present.

Last Updated: Apr 26, 2020, 5:27 AM