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

String interpolation in C Sharp (C#)

Choose your learning style9 modes available
Introduction

String interpolation helps you easily put values inside text without extra steps.

When you want to show a message with numbers or names inside it.
When you build sentences that change based on data.
When you want your code to be easier to read and write.
When you combine text and variables in one line.
When you want to avoid confusing plus signs (+) for joining text.
Syntax
C Sharp (C#)
string message = $"Hello, {name}! You have {count} new messages.";
Start the string with a $ sign before the opening quote.
Put variables or expressions inside curly braces { } where you want their values.
Examples
Insert a simple variable inside the text.
C Sharp (C#)
string name = "Anna";
string greeting = $"Hi, {name}!";
Show a number inside a sentence.
C Sharp (C#)
int apples = 5;
string message = $"You have {apples} apples.";
You can put simple math inside the braces.
C Sharp (C#)
int a = 3, b = 4;
string result = $"Sum is {a + b}.";
Format dates inside the string using a colon and format code.
C Sharp (C#)
DateTime today = DateTime.Now;
string date = $"Today is {today:MMMM dd, yyyy}.";
Sample Program

This program greets the user by name and tells how many new messages they have using string interpolation.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        string name = "Sam";
        int messages = 3;
        string output = $"Hello, {name}! You have {messages} new messages.";
        Console.WriteLine(output);
    }
}
OutputSuccess
Important Notes

You can put any expression inside the braces, not just variables.

Use @ before $ for multi-line interpolated strings: @$"..."

Be careful with curly braces if you want to show them literally: use double braces {{ or }}.

Summary

String interpolation makes combining text and values easy and clear.

Use $ before the string and put variables inside { }.

It works with variables, expressions, and formatting.