Tuesday, August 9, 2022

C# @ - Verbatim string lieterals

 

Literals

Literals are how you hard-code strings into C# programs. There are two types of string literals in C# - regular string literals and verbatim string literals. Regular string literals are similar to those in many other languages such as Java and C - they start and end with ", and various characters (in particular, " itself, \, and carriage return (CR) and line feed (LF)) need to be "escaped" to be represented in the string. Verbatim string literals allow pretty much anything within them, and end at the first " which isn't doubled. Even carriage returns and line feeds can appear in the literal! To obtain a " within the string itself, you need to write "". Verbatim string literals are distinguished by having an @ before the opening quote. Here are some examples of the two types of literal, and what they amount to:

Regular literalVerbatim literalResulting string
"Hello"@"Hello"Hello
"Backslash: \\"@"Backslash: \"Backslash: \
"Quote: \""@"Quote: """Quote: "
"CRLF:\r\nPost CRLF"@"CRLF:
Post CRLF"
CRLF:
Post CRLF

Note that the difference is only for the compiler's sake. Once the string is in the compiled code, there's no such thing as a verbatim string literal vs a regular string literal.

No comments:

Post a Comment