C# String Format() Method

The Format() method in C# is used to create a string that contains formatted representations of specified objects. It returns a new string that is created by replacing format items in a specified string with the string representation of specified objects.

The syntax of the Format() method is as follows:

string.Format(format, arg0, arg1, ...);
Sour‮ww:ec‬w.theitroad.com

Here, format is a string that contains one or more format items, and arg0, arg1, ... are objects whose string representations will be substituted for the corresponding format items in the format string.

The format items in the format string are identified by braces {}. Within the braces, you can specify a number indicating the zero-based index of the object to be substituted. For example, {0} indicates the first object, {1} indicates the second object, and so on. You can also specify a format string after the index, separated by a colon :, to format the string representation of the object.

Here's an example of using the Format() method:

string name = "Alice";
int age = 30;
string message = string.Format("My name is {0} and I am {1} years old.", name, age);
Console.WriteLine(message);  // Output: "My name is Alice and I am 30 years old."

In this example, the Format() method is used to create a new string that contains the values of the name and age variables in the format string "My name is {0} and I am {1} years old.". The resulting string is then assigned to the message variable and printed to the console using the WriteLine() method.

You can use various format specifiers to format the string representation of the objects being substituted. Some common format specifiers include:

  • d: format an integer as a decimal number
  • f: format a floating-point number as a fixed-point number
  • c: format a character as a Unicode character
  • s: format an object as a string

For example, to format a decimal number with two decimal places, you can use the format string {0:f2}:

decimal price = 12.3456m;
string message = string.Format("The price is {0:f2}.", price);
Console.WriteLine(message);  // Output: "The price is 12.35."

In this example, the Format() method is used to create a new string that formats the price variable with two decimal places using the {0:f2} format string. The resulting string is then printed to the console.