String interpolation is done by using the dollar sign ($), followed by curly braces ({}) to enclose expressions, this article will discuss how to do string interpolation using the dollar sign in C#.
String Interpolation Using $ in C#
To use string interpolation in C#, you can prefix a string literal with the $ character and after that, you can include expressions inside curly braces {} within the string literal to interpolate their values, here is an example:
class Program {
static void Main(string[] args) {
string name = "SAM";
int age = 25;
Console.WriteLine($"My name is {name} and I am {age} years old");
}
}
In this code, the string literal “My name is {name} and I am {age} years old” is interpolated with the values of the variable name and age, the result of this code is:
You can also insert expressions inside the curly braces when using string interpolation; as an example, consider the following:
class Program {
static void Main(string[] args) {
int x = 10;
int y = 20;
Console.WriteLine($"The sum of {x} and {y} is {x + y}.");
}
}
In this code, the expression {x + y} is included inside the interpolated string literal, the result of this code would be:
Conclusion
The string interpolation in C# is a powerful way to embed expressions inside string literals. By using the $ character followed by curly braces {}, developers can create more readable and maintainable code that is easier to write and understand. String interpolation simplifies string concatenation and improves the readability of code by eliminating the need for complex string concatenation expressions.