C# String Format

The String.Format() method in C# is used to create formatted strings using placeholders. This method is useful for formatting numbers, dates, and inserting variable values into strings.

Key Topics

1. Basic Formatting

Example: Using Placeholders

string name = "Alice";
int age = 30;
string message = String.Format("Name: {0}, Age: {1}", name, age);
Console.WriteLine(message); // Outputs: Name: Alice, Age: 30

2. Format Specifiers

Format specifiers allow you to control the formatting of numbers and dates.

Example: Formatting Numbers and Dates

double price = 123.456;
DateTime date = DateTime.Now;
string formattedPrice = String.Format("Price: {0:C2}", price);
string formattedDate = String.Format("Date: {0:MMMM dd, yyyy}", date);
Console.WriteLine(formattedPrice); // Outputs: Price: $123.46
Console.WriteLine(formattedDate);  // Outputs: Date: (current date in specified format)

3. Composite Formatting

You can include expressions and calculations within the placeholders.

Example: Composite Formatting with Expressions

int a = 5;
int b = 10;
string result = String.Format("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine(result); // Outputs: 5 + 10 = 15

Key Takeaways

  • String.Format() uses placeholders to insert variables into strings.
  • Format specifiers control the display format of numbers and dates.
  • Composite formatting allows for expressions within placeholders.
  • String interpolation ($"") is a more modern alternative.