String Interpolation in C#


String interpolation in C# is a feature that allows you to embed expressions inside string literals, providing a more readable and concise way to format strings. It was introduced in C# 6.0 and has become a popular way to construct strings due to its simplicity and clarity.

Syntax

String interpolation uses the $ character followed by a string literal. Inside the string literal, expressions are enclosed in curly braces {}.

The following types of String interpolation we can use.

  1. Basic Interpolation
  2. Expression Evaluation
  3. Formatting
  4. Escape Characters
  5. Multiline Strings

1. Basic Interpolation

Example

string name = "Rohatash";
int age = 30;
string greeting = $"Hello, my name is {name} and I am {age} years old.";
Console.WriteLine(greeting);

2. Expression Evaluation

You can include expressions within the curly braces.

Example

int a = 5;
int b = 10;
string result = $"The sum of {a} and {b} is {a + b}.";
Console.WriteLine(result);

3. Formatting

You can format numbers, dates, and other values within the interpolation.

Example

decimal price = 123.456m;
DateTime date = DateTime.Now;
string formattedString = $"Price: {price:C}, Date: {date:MMMM dd, yyyy}";
Console.WriteLine(formattedString);

4. Escape Characters

If you need to include a curly brace { or } in the string, you can escape it by doubling the brace.

Example


string example = $"To include a brace, use {{ and }}.";
Console.WriteLine(example);

5. Multiline Strings

String interpolation works with verbatim strings as well (using @), which can be useful for multiline strings.

Example


string name = "Rohatash";
string address = @"123 Main St
Apt 4B
Noida, INDIA";
string message = $@"Dear {name},

Your package has been shipped to:
{address}

Thank you for your order!";
Console.WriteLine(message);

Prev Next