C# - String Formatting
String formatting in C# allows you to create formatted strings by combining text with placeholders for variables or expressions. The string.Format method and string interpolation ($"{...}" syntax) are the two main approaches for string formatting in C#. Here's how to use both methods:
1. String.Format Method:
The 'string.Format' method takes a composite format string and a variable number of arguments. The format string contains placeholders represented by curly braces {}
that are replaced by the corresponding arguments.
string name = "John";
int age = 30;
string formattedMessage = string.Format("Hello, {0}! Your age is {1} years.", name, age);
Console.WriteLine(formattedMessage); // Output: "Hello, John! Your age is 30 years."
2. String Interpolation:
String interpolation is a more concise and expressive way of formatting strings. It allows you to embed expressions or variables directly within the string using the '$' symbol and curly braces '{}'.
string name = "John";
int age = 30;
string interpolatedMessage = $"Hello, {name}! You are {age} years old.";
Console.WriteLine(interpolatedMessage); // Output: "Hello, John! You are 30 years old."
3. Formatting Numeric Values:
You can apply formatting options to numeric values in the placeholders to control their appearance, such as specifying the number of decimal places or using currency symbols.
double price = 19.99;
string formattedPrice = string.Format("The price is: {0:C}", price);
Console.WriteLine(formattedPrice); // Output: "The price is: $19.99"
string formattedDecimal = string.Format("Value: {0:F2}", 123.456789);
Console.WriteLine(formattedDecimal); // Output: "Value: 123.46"
4. DateTime Formatting:
For formatting DateTime
values, you can use custom format specifiers or predefined format strings.
using System;
class Program
{
static void Main()
{
// Create a DateTime object representing a specific date and time
DateTime myDateTime = new DateTime(2023, 11, 16, 15, 30, 0);
// Use string.Format to format the DateTime
string formattedDateTime = string.Format("{0:yyyy-MM-dd HH:mm:ss}", myDateTime);
Console.WriteLine("Formatted DateTime: " + formattedDateTime);
}
}
In this example:
-
We create a
DateTime
object named myDateTime
representing a specific date and time (November 16, 2023, at 3:30 PM).
- We use
string.Format
to format the DateTime
. Inside string.Format
, we provide a format string {0:yyyy-MM-dd HH:mm:ss}
.
- The format string
{0:yyyy-MM-dd HH:mm:ss}
specifies how the DateTime
should be formatted. It formats the date as yyyy-MM-dd
and the time as HH:mm:ss
.
- The formatted
DateTime
is stored in the formattedDateTime
variable and then printed to the console.
This demonstrates how to use string.Format
to format a DateTime object with custom formatting in C#.
5. Composite Formatting:
Composite formatting allows you to apply format specifiers directly in the placeholders.
int value = 42;
string formattedValue = string.Format("Value: {0:D5}", value);
Console.WriteLine(formattedValue); // Output: "Value: 00042"
Both string interpolation and string.Format
can be powerful tools for creating well-formatted output in your C# applications. They make it easier to build complex strings by combining static text with dynamic values, and they offer a variety of formatting options to meet different requirements. Choose the method that suits your preference and the specific needs of your project.