String Interpolation in C#
Introduction
String interpolation is a feature in C# that allows you to insert variable values directly into strings. This makes your code cleaner and easier to read. In this tutorial, we will cover the basics of string interpolation and provide various examples to illustrate its usage.
Basic Syntax
In C#, string interpolation is done using the $ symbol followed by a string in double quotes. Within the string, you can embed expressions inside curly braces { }.
Example:
string name = "John"; int age = 30; string greeting = $"Hello, my name is {name} and I am {age} years old."; Console.WriteLine(greeting);
Output:
Hello, my name is John and I am 30 years old.
Expressions in Interpolation
You can include any valid C# expression within the curly braces. This includes mathematical operations, method calls, and even conditional statements.
Example:
int a = 5; int b = 10; string result = $"The sum of {a} and {b} is {a + b}."; Console.WriteLine(result);
Output:
The sum of 5 and 10 is 15.
Formatting Strings
String interpolation also allows you to format the embedded values. You can use format specifiers to control the appearance of numbers, dates, and other values.
Example:
double price = 123.456; string formattedPrice = $"The price is {price:C2}."; Console.WriteLine(formattedPrice);
Output:
The price is $123.46.
Nested Interpolation
You can nest interpolated strings within each other to create more complex strings. This is useful when you need to build strings dynamically based on various conditions.
Example:
string firstName = "Jane"; string lastName = "Doe"; string fullName = $"{firstName} {lastName}"; string greeting = $"Hello, {fullName.ToUpper()}!"; Console.WriteLine(greeting);
Output:
Hello, JANE DOE!
Escaping Braces
If you need to include curly braces in your string, you can escape them by doubling them. This is useful when you want to include literal braces in your output.
Example:
string message = $"The set notation is {{1, 2, 3}}."; Console.WriteLine(message);
Output:
The set notation is {1, 2, 3}.
Conclusion
String interpolation is a powerful and convenient feature in C# that simplifies the process of creating dynamic strings. By using the $ symbol and embedding expressions within curly braces, you can create readable and maintainable code with ease. We hope this tutorial has helped you understand the basics and advanced uses of string interpolation.