create a template string in csharp

In C#, a template string is created using the string interpolation syntax, which allows you to embed expressions within string literals. Here's an example:

main.cs
string name = "Alice";
int age = 30;
string message = $"My name is {name} and I am {age} years old.";
102 chars
4 lines

In this example, the interpolated string literal begins with a $ character, followed by a string that contains expressions enclosed in curly braces {}. The expressions can be simple variables, properties, or method calls. The expressions are evaluated at runtime and their values are substituted into the final string.

You can also use format strings to control the formatting of values in the interpolated string. Here's an example:

main.cs
double price = 29.99;
string message = $"The price is {price:C2}.";
68 chars
3 lines

In this example, the format string :C2 is appended to the variable name in the interpolated string. This causes the value to be formatted as a currency value with two decimal places.

String interpolation is a powerful feature that allows you to create complex strings with ease. It can also help you to write safer and more maintainable code by reducing the likelihood of errors caused by manual string concatenation.

gistlibby LogSnag