String.Format() is a method in C# that allows to create a formatted string using placeholders to represent the values that will be inserted into the string. This method provides a way to combine string literals and variables or expressions to create a formatted string in a more readable and flexible way.
How to use String.Format Method in C#
In format string with the values of the corresponding arguments and returns the resulting, it is a method that provides a powerful and flexible way to format strings in C# and is widely used in applications that require string manipulation and output formatting.
The <format string> parameter is a composite format string that defines the text to be output and the placeholders for the arguments to be inserted. The placeholders are represented by braces {} and can include format specifiers to control the display of the values.
The <arg0>, <arg1>, …, <argN> parameters are the arguments to be inserted into the string. They can be of any type, and their values are converted to strings and inserted into the format string at the corresponding placeholders.
Let’s consider the following code that uses this function to create a formatted string:
class Program
{
static void Main(string[] args)
{
// Initialize variables
string name = "Mark";
int age = 25;
int ID = 7836;
// Use String.Format to create formatted output string
string output = String.Format("Name: {0}, Age: {1}, ID: {2}", name, age, ID);
// Print the output string to the console
Console.WriteLine(output);
}
}
In this example, we first declare three variables: name, age, and salary and then use the String.Format() function to format these values into a string.
The first argument to String.Format() is a string that specifies the desired output format and, in this case, the format string contains three placeholders: {0} for the name, {1} for the age, and {2:C} for the salary. The C format specifier formats the salary value as a currency, using the current culture’s currency symbol.
The remaining arguments to String.Format provide the values to substitute into the placeholders. We pass in name, age, and salary as the second, third, and fourth arguments, respectively. The String.Format method then returns the formatted string, which we store in the output variable, here is the output of the code:
Conclusion
The String.Format() is a method in C# that allows you to create a formatted string by replacing placeholders in a format string with values provided as arguments. By using formatting options in the placeholders, you can control the way the output value is displayed. This method is a convenient way to create formatted output in your C# applications.