0
0
C Sharp (C#)programming~5 mins

String interpolation and formatting in C Sharp (C#)

Choose your learning style9 modes available
Introduction

String interpolation and formatting help you create text that includes values from variables easily and clearly.

When you want to show a message that includes numbers or names stored in variables.
When you need to build a sentence that changes based on user input.
When you want to format numbers or dates nicely inside text.
When you want to combine text and values without using many plus signs (+).
Syntax
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.

Examples
Simple interpolation with variables inside a string.
C Sharp (C#)
string name = "Alice";
int age = 30;
string message = $"Name: {name}, Age: {age}";
Formats the price as currency using :C.
C Sharp (C#)
double price = 12.5;
string formatted = $"Price: {price:C}";
Formats the date to show full month name, day, and year.
C Sharp (C#)
DateTime today = DateTime.Now;
string date = $"Today is {today:MMMM dd, yyyy}";
You can use expressions inside the braces.
C Sharp (C#)
int x = 5, y = 10;
string sum = $"Sum of {x} and {y} is {x + y}";
Sample Program

This program shows how to use string interpolation to include variables and format numbers and dates in a friendly message.

C Sharp (C#)
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);
    }
}
OutputSuccess
Important Notes

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.

Summary

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.