I often see curly braces in a string usually containing a number, such as:
string something = "I have {0} cats";
Whilst I can work out what this means, I can say I've never read any documentation relating to its useage. The c# string documentation seems to be void of any information relating to these. Can anyone point me in the right direction?
*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.)
It's the normal format string used by String.Format
, and is called "composite formatting". For more info about it, have a look here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With