C# String Interpolation

In C# programming language, the $ symbol is employed to recognize a string literal as an interpolated string. This feature enables the direct inclusion of variables and expressions within a string by enclosing them in curly braces {}. Utilizing interpolated strings enhances code readability and simplifies maintenance in contrast to string concatenation. Below is the standard format of an interpolated string.

The CSS code shown below creates a diagram with a background gradient, rounded corners, padding, margin, and centered text alignment:

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

Syntax:

It has the following syntax.

Example

$ "<text> { < interpolated-expression > [,< field-width >] [< :format-string >] } < text > ... "

In this format, the curly brackets {} are employed to contain and distinguish variables within the interpolated string.

C# Simple String Interpolation Example

Let's consider a scenario to demonstrate how string interpolation works in C#.

Example

Example

using System;

public class C# Tutorial

{

    public static void Main ()

    {

        string name = "Johnson";

        int age = 25;

        string city = "New York";

        // Using string interpolation

        string info = $"My name is {name}, I am {age} years old, and I live in {city}.";

        Console.WriteLine(info);

    }

}

Output:

Output

My name is Johnson, I am 25 years old, and I live in New York.

Explanation:

In this instance, we've defined three variables: names, age, and city, and initialized them with values. Subsequently, a string variable "info" has been constructed using string interpolation, enclosing the variables within curly braces {}. Lastly, the output has been displayed by employing the Console.WriteLine method.

Using Expressions and Formatting in String Interpolation

In C#, String Interpolation enables the execution of computations and function invocations within strings, facilitating precise formatting within the interpolated string. These functionalities contribute to improving the effectiveness and clarity of the code.

C# String Interpolation Example using Expressions and Formatting

Let's consider a scenario to showcase string interpolation in C# by utilizing expressions and formatting.

Example

Example

using System;

public class C# Tutorial

{

    public static void Main()

    {

        string product = "Laptop";

        double price = 70000.80;

        int quantity = 2;

        // Using expression and formatting inside string interpolation

        string mes = $"The Product is {product}\nThe Quantity is {quantity}\nThe Total Prices are {(price * quantity):0.00}";

        Console.WriteLine(mes);

    }

}

Output:

Output

The Product is Laptop

The Quantity is 2

The Total Prices are 140001.60

Explanation:

In this instance, we've generated a basic C# application. Initially, we've defined three variables: item, cost, and amount. Following that, we've employed string interpolation to embed variable contents and merge text with variable values. Additionally, we've implemented the numeric format specifier (0.00). Ultimately, we've employed the Console.WriteLine function to display the result.

Advantages of String Interpolation in C#

There are several advantages of string interpolation in C#. Some of them are as follows:

  • It helps to make the code more readable and maintainable.
  • We have no need to use the + for concatenation.
  • It reduces the syntax errors and improves performance.
  • It helps in logging and dynamic UI messages easily.
  • It makes debugging and error tracking easier because interpolated strings are simple to read and understand.
  • Difference between String Concatenation and String Interpolation

The primary variance between string concatenation and string interpolation in C# includes the following distinctions.

Features String Concatenation String Interpolation
Syntax It uses the + operator to combine strings and variables.Example:"I am" + name It uses the $ symbol before the string and curly braces {} for variables.Example:$"I am {name}
Introduced It is available in all the C# versions. It is introduced in C# 6.0.
Readability It is less readable, especially for multiple variables. It is more readable and has a clean syntax.
Performance It is slower when multiple strings are concatenated. It is faster than concatenation.

Limitations of String Interpolation in C#

There are several limitations of String Interpolation in C#. Some of them are as follows:

  • String interpolation in C# cannot be utilized in a const declaration because const values must be known at compile time.
  • We can use string interpolation to create a new string. It can slow down the program when we use it many times inside a loop.
  • String interpolation is available only from C# 6.0 version and later. The older versions of C# do not support string interpolations.
  • We cannot use string interpolation inside attributes because attributes accept only fixed (constant) values.
  • Interpolated strings are difficult to translate into other languages because variables are mixed with text.
  • Conclusion

In summary, string interpolation is commonly favored in C# over string concatenation due to its straightforward and template-driven syntax. This approach enhances code readability and ease of maintenance. The output of string interpolation is a string value, making it a popular choice for logging purposes in contemporary C# applications.

C# String Interpolation FAQs

1) What is string Interpolation in C#?

In C#, string interpolation enables the insertion of variables into strings using a straightforward template syntax. The output of an interpolated string is a unified string. This method serves as an alternative approach to string concatenation and is commonly employed for generating formatted output, logging information, and dynamically showcasing variable values.

In C#, string interpolation differs from string concatenation by allowing variables and expressions to be directly embedded within a string literal, using the $ symbol before the string. This enables easier and more readable string formatting compared to concatenating multiple strings together.

In C#, combining strings is frequently employed using the + operator to merge the string values. This method involves using the $ symbol along with curly braces {} to embed variables or expressions directly within the string.

The introduction of string interpolation in C# occurred in the year ```

$ "<text> { < interpolated-expression > [,< field-width >] [< :format-string >] } < text > ... "

Example


In C#, the concept of string interpolation was first introduced in C# version 6.0. This feature plays a crucial role in improving the efficiency and readability of string manipulation in C#.

4) Is it possible to apply formatting to values using string interpolation in C#?

Yes, in C#, string interpolation enables us to incorporate values within the string using format specifiers.

double salary = 45890.75;

DateTime today = DateTime.Now;

Console.WriteLine($" Salary: {salary:C} ");

Console.WriteLine($" Date: {today:dd-MM-yyyy} ");

Output


5) Is it possible to include an expression within a string interpolation in C#?

Yes, we have the ability to utilize expressions for executing calculations and invoking methods. This enables us to incorporate precise formatting within the interpolated string, providing the opportunity to implement tailored formatting and enhance the string's dynamism and adaptability.

int a = 10, b = 20;

Console.WriteLine("The sum of " + a + " and " + b + " is " + (a + b) + ".");

Output


Output:

The sum of 10 and 20 is 30.

Example


Input Required

This code uses input(). Please provide values below: