*With C# 6.0 & friends, curly braces aren't just for string.Format
any more! Now they can denote interpolated strings, where you can mix in C# objects and code without all the string.Format
& {0} {1} {2}
overhead.
NOTE: Interpolated strings start with a dollar sign: $
From the language reference page linked above:
Used to construct strings. An interpolated string looks like a
template string that contains interpolated expressions. An
interpolated string returns a string that replaces the interpolated
expressions that it contains with their string representations.
The arguments of an interpolated string are easier to understand than
a composite format string. For example, the interpolated string
Console.WriteLine($"Name = {name}, hours = {hours:hh}");
contains two interpolated expressions, '{name}' and '{hours:hh}'. The
equivalent composite format string is:
Console.WriteLine("Name = {0}, hours = {1:hh}", name, hours);
Note: If you didn't know, Console.WriteLine
has a sort of built-in string.Format
, which might not be obvious in the above example if you didn't realize that going in.
If you wanted to get the same string out without relying on Console.WriteLine magic, it might be easier to read that this...
string message = $"Name = {name}, hours = {hours:hh}"; // interpolated
... is equivalent to...
string message = string.Format("Name = {0}, hours = {1:hh}", name, hours); // old school
The structure of an interpolated string is:
$"<text> {<interpolated-expression> [,<field-width>] [<:format-string>] } <text> ..."
where:
- field-width is a signed integer that indicates the number of characters in the field. If it is positive, the field is right-aligned; if negative, left-aligned.
- format-string is a format string appropriate for the type of object being formatted. For example, for a DateTime value, it could be a standard date and time format string such as "D" or "d".
You can use an interpolated string anywhere you can use a string
literal. The interpolated string is evaluated each time the code with
the interpolated string executes. This allows you to separate the
definition and evaluation of an interpolated string.
To include a curly brace ("{" or "}") in an interpolated string, use
two curly braces, "{{" or "}}".
* As @Ben points out in a comment, above. (Sorry, missed that on the way in.)