String Interpolation in C#
Programmers can incorporate expressions into string literals using the C# functionality known as string interpolation. Complex string messages with variables and expressions are made easier to generate as a result. The '$' character is used in C# string interpolation to indicate interpolated expressions within a string literal. We will examine string interpolation in C# and present examples in this blog article.
Basic syntax
String interpolation is used by prefixing a string literal with the '$' character and then including one or more expressions inside curly braces.
Here's an illustration:
int age = 30;
Console.WriteLine($"My name is {name} and I am {age} years old.");
In this example, we have a string literal with two expressions enclosed by curly brackets. At runtime, the expressions are evaluated and the resulting values are placed into the string.
Output:
Formatting expressions
The next example illustrates how to format the string. Here inside the curly braces after the pi variable the colon (:) symbol has been added followed by F2. the F2 points 2 decimal places.
Here's an illustration:
Console.WriteLine($"The value of pi is {pi:F2}.");
In this example, the double variable pi is formatted using the format string "F2," which denotes two decimal places.
Output:
Conditional expressions
You can use the conditional expression inside the interpolated expression. In the following example, the age is not one then year’s’ will display. The character ‘s’ will appended with word year
Here's an illustration:
int age = 1;
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
In this case, an int variable age is used to include or exclude an's' at the end of the word 'year' based on whether it is equal to one.
Output:
Combining expressions
Multiple expressions can be combined within a single interpolated string. For example, you can provide a person's name and age, as well as the current date and time.
Here's an illustration:
int age = 30;
DateTime date = DateTime.Now;
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
Output:
Using quotes and special characters
We have a string variable name, an int variable age, and a DateTime variable date in this example. To construct a message that includes the person's name, age, and the current date and time, we employ all three variables within a single interpolated string.
Here's an illustration:
double y = 4.2;
Console.WriteLine($"The point \"{x}, {y}\" is {Math.Sqrt(x * x + y * y)} units from the origin.");
Output:
Conclusion
The string interpolation feature helps the developers to easily embed the variable with strings
I hope this helps you. Keep coding.
Comments
Post a Comment