C# String Interpolation: Concise and Readable String Formatting

Enhance your C# string formatting with string interpolation. This tutorial demonstrates how to embed variables and expressions directly within strings using the $ syntax, resulting in cleaner, more readable, and easier-to-maintain code.



Using String Interpolation in C#

C# string interpolation provides a concise and readable way to embed variables and expressions directly within strings. It simplifies string formatting and makes your code easier to understand.

String Interpolation Syntax

Interpolated strings are created by preceding a string literal with a dollar sign ($) and enclosing variables or expressions within curly braces `{}`:


string message = $"Hello, {name}! You are {age} years old.";

The values of `name` and `age` will be inserted into the string at runtime.

Example: Simple String Interpolation


using System;

public class StringInterpolationExample {
    public static void Main(string[] args) {
        string name = "Alice";
        int age = 25;
        string message = $"{name} is {age} years old.";
        Console.WriteLine(message); //Output: Alice is 25 years old.
    }
}

This example demonstrates how to create an interpolated string and print it to the console. The output clearly shows the values substituted into the string.

Comparison with Composite Formatting

String interpolation offers a more readable alternative to composite formatting:


//Composite Formatting
string message = string.Format("Name: {0}, Age: {1}", name, age);

//String Interpolation
string message = $"{name} is {age} years old.";

String interpolation is generally preferred for its cleaner syntax.