1. Overview
Special characters are predefined context characters that modify program elements (text strings, identifiers, or attribute names) that have such characters inserted first. C# supports the following special characters:
- @: verbatim string identifier character
- $: Insert string characters
2. $-- String interpolation
$
Characters identify the string literal as an interpolated string. An interpolated string is a string text that may contain an interpolated expression. When parsing an interpolated string into a result string, the items with the interpolated expression are replaced with the string representation of the expression result.
String interpolation provides a more readable and convenient way to format strings. It's easier to set up than string composite formats.
public static void Main(string[] arg) { var name = "Mark"; var date = ; ("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, , date); ($"Hello, {name}! Today is {}, it's {date:HH:mm} now."); }
Starting from C# 10, interpolated strings can be used to initialize constant strings. This is only possible if all interpolated expressions in the interpolated string are also constant strings.
2.1 Structure of interpolated strings
To identify a string as an interpolated string, prefix it with the string$
symbol. String literal begins$
and"
There cannot be any spaces between them.
The structure of the item with an interpolated expression is as follows:
{<interpolationExpression>[,<alignment>][:<formatString>]}
-
interpolationExpression
Generate expressions that require formatting.null
The string representation of。
-
alignment
A constant expression whose value defines the minimum number of characters in the string representation of the expression result. If the value is positive, the string representation is right-aligned; if the value is negative, the string is left-aligned. -
formatString
Format string supported by expression result type.
public static void Main(string[] arg) { ($"|{"Left",-7}|{"Right",7}|"); const int FieldWidthRightAligned = 20; ($"{,FieldWidthRightAligned} - default formatting of the pi number"); ($"{,FieldWidthRightAligned:F2} - display only three decimal digits"); }
Starting with C# 11, line breaks can be used in interpolated expressions to make the expression's code more readable.
The following example shows how line breaks improve the readability of expressions involving pattern matching:
public static void Main(string[] arg) { var safetyScore = 80; string message = $"The usage policy for {safetyScore} is" + $" {safetyScore switch { > 90 => "Unlimited usage", > 80 => "General usage, with daily safety check", > 70 => "Issues must be addressed within 1 week", > 50 => "Issues must be addressed within 1 day", _ => "Issues must be addressed before continued use", }}"; (message); }
2.2 Interpolate the original string literals
Starting with C# 11, you can use interpolated original string literals. As shown in the following example:
int X=2; int Y=3; var pointMessage = $"""The point"{X},{Y}" is {(X*X+Y*Y):F3} from the origin"""; (pointMessage);
To embed the result string{
and}
Characters, please let the original string literals be inserted into multiple$
Start with a character. Any length is short when doing this$
Character count{
and}
The character sequences are embedded in the result string. To include any interpolated expressions in this string, you need to use the$
Number of braces with the same number of characters.
As shown in the following example:
int X = 2; int Y = 3; var pointMessage = $$"""{The point {{{X}}, {{Y}}} is {{(X * X + Y * Y):F3}} from the origin}"""; (pointMessage);
Interpolate the original string literals with two$
Start with a character. Need to put each interpolated expression in double braces{{
and}}
between. Single braces are embedded in the result string, if repeated{
or}
Characters are embedded in the result string, please use the corresponding added$
The number of characters to specify the literal of the interpolated original string.
2.3 Special characters
To include braces "{"or"}" in text generated by interpolated strings, use two braces, namely "{{" or "}}". For more information.
Because colons (":") have special meanings in interpolated expressions, in order to use conditional operators in interpolated expressions, put the expression in parentheses.
The following example demonstrates how to include braces in the result string. The following example shows how to use the conditional operator:
string name = "Horace"; int age = 34; ($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{"); ($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Interpolate verbatim string to$
and@
Start with a character. Can be used in any order$
and@:
$@"..."
and@$"..."
All are valid interpolated word-by-word strings.
2.4 Interpolated string compilation
Starting with C# 10 and .NET 6, the compiler checks whether the interpolated string is assigned to a type that meets the interpolated string handler mode requirements. An interpolated string handler is a type of converting interpolated strings into result strings. When the type of the interpolated string is string, it is processed by.
Before C# 10, if the interpolated string type was String, it was usually converted to a method call. If the behavior of the analysis is equivalent to concatenation, the compiler can replace it with.
If the interpolated string type is IFormattable or FormattableString, the compiler generates a call to the method.
3. @-- literal string identifier
@
Special characters are used as primitive identifiers. Use it in the following ways:
- Instructs the string to interpret the original meaning.
@
Characters define the literal identifier in this example. Simple escape sequence, hexadecimal escape sequence, andUnicode
Escape sequences are all interpreted literally. Only the quotation escape sequence ("") will not be interpreted literally; because it generates a double quote. also. If it is a verbatim string, the braces escape the sequence ({{
and}}
) is not interpreted literally; they generate single brace characters.
string filename1 = @"c:\documents\files\"; string filename2 = "c:\\documents\\files\\"; (filename1); (filename2);
- Use C# keywords as identifiers.
@
Characters can be used as prefixes for code elements, and the compiler will interpret this code element as an identifier rather than a C# keyword.
string[] @for={"John","James","Joan","Jamie"}; for(int ctr = 0; ctr<@;ctr++) { ($"Here is your gift, {@for[ctr]}!"); }
Make the compiler distinguish between two attributes in case of naming conflicts. Attributes are derived from
Attribute
class. Its type name usually contains a suffixAttribute
, but the compiler will not cast the conversion.
4. """ - original string text
The original string literal is in at least three double quotes (“
) Characters start and end:
var singleLine = """This is a "raw string literal". It can contain characters like \, ' and ".""";
The original string literal can contain multiple lines:
var xml = """ <element attr="content"> <body> </body> </element> """;
The following rules control the explanation of the literals of multiple lines of raw strings:
- Left and right quotation characters must be in their respective lines
- Any space to the left of the right quotes will be removed from all lines of the original string literal.
- The spaces following the left quotation marks in the same line are ignored.
- String literals contain only space lines following left quotes
You may need to create a raw string literal containing three or more consecutive double quote characters. The original string literal can start and end the sequence of at least three double quote characters. If the string literal contains three consecutive double quotes, the original string literal starts and ends with four double quote characters:
var moreQuotes = """" As you can see,"""Raw string literals""" can start and end with more than three double-quotes when needed."""";
The original string literal can also be used in conjunction with interpolated strings to embed in the output string.{
and}
character. Use multiple in interpolated original string literals$
Characters to embed in the output string{
and}
characters without escaping them.
This is the article about this article that will introduce you to the special characters in C#. For more relevant C# special characters, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!