What is String.Format() method in C#?

Overview

The String.Format() method in C# is used to format a string. This method takes a format string and an object array as parameters and formats the string accordingly. The format string contains placeholders for the objects in the object array.

For example, if we have a string "{0} is a {1}" and an object array containing two strings, "John" and "programmer", the String.Format() method will return the string "John is a programmer".

This method is often used to format user-input data before it is displayed or stored. For instance, if we have a text box for users to input their date of birth, we can use the String.Format() method to format the data into a more readable format before displaying it or storing it in a database.

Syntax

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

public static string Format(string format, params object[] args)
Syntax of String.Format() method

Parameters

The String.Format() method takes the following parameters:

  • format: This is the format string.
  • args: This is an object array containing the objects to be formatted.

Return value

The String.Format() method returns a string containing the formatted objects.

Example

Let's take a look at a simple example to see how the String.Format() method works. In this example, we have a string containing placeholders for two objects. We also have an object array containing two strings. The String.Format() method formats the string, using the objects in the object array.

using System;
class HelloWorld
{
static void Main()
{
string str = "Hello, {0}! Welcome to {1}.";
object[] args = new object[] {"John", "Educative"};
string formattedStr = String.Format(str, args);
Console.WriteLine(formattedStr);
}
}

Explanation

In the code above:

  • Line 6: We have a string with two placeholders, {0} and {1}.
  • Line 7: We have an object array containing two strings: "John" and "Educative".
  • Line 8: We format the string using the objects in the object array using the String.Format() method.

Free Resources