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.cs102 chars4 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.cs68 chars3 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