In C#, formatted strings can be created using the String.Format method or interpolated strings. Here are examples of both approaches:
Using String.Format Method
string name = "John";
int age = 30;
string formattedString = string.Format("The person's name is {0} and their age is {1}.", name, age);
Console.WriteLine(formattedString);
In the above example, {0} and {1} are placeholders for the name and age variables respectively.
Interpolated Strings
string name = "Emily";
int age = 25;
string interpolatedString = $"The person's name is {name} and their age is {age}.";
Console.WriteLine(interpolatedString);
In the interpolated string, the variables name and age are directly embedded within the string using the $ symbol.
using System;
class Program
{
static void Main()
{
// Using interpolated strings
string name = "Jane";
string dayOfWeek = DateTime.Now.DayOfWeek.ToString();
string formattedString = $"Hello, {name}! Today is {dayOfWeek}.";
Console.WriteLine(formattedString);
}
}
Leave a comment