String interpolation and formatting help you create text that includes values from variables easily and clearly.
String interpolation and formatting in C Sharp (C#)
string result = $"Hello, {name}! You have {count} new messages.";Use the $ symbol before the string to start interpolation.
Place variables or expressions inside curly braces { } where you want their values to appear.
string name = "Alice"; int age = 30; string message = $"Name: {name}, Age: {age}";
:C.double price = 12.5; string formatted = $"Price: {price:C}";
DateTime today = DateTime.Now;
string date = $"Today is {today:MMMM dd, yyyy}";int x = 5, y = 10; string sum = $"Sum of {x} and {y} is {x + y}";
This program shows how to use string interpolation to include variables and format numbers and dates in a friendly message.
using System; class Program { static void Main() { string user = "Bob"; int messages = 3; double balance = 45.678; DateTime now = DateTime.Now; string output = $"Hello, {user}! You have {messages} new messages.\n" + $"Your balance is {balance:C2}.\n" + $"Today is {now:dddd, MMMM dd, yyyy}."; Console.WriteLine(output); } }
String interpolation was introduced in C# 6.0 and is now the easiest way to build strings with variables.
You can add formatting inside the braces after a colon, like {value:C2} for currency with 2 decimals.
Remember to use \n for new lines inside strings.
Use $"...{variable}..." to insert variables directly into strings.
You can format numbers and dates inside the braces with a colon and format code.
String interpolation makes your code easier to read and write compared to older methods.