Search notes:

C-Sharp: verbatim and interpolated strings

The special character @

In C-Sharp, the special character @ can be placed on the left side of identifiers and strings.
If placed on the left side of a string, all characters except "" (which produces a ") are interpreted literally, notably the backslash \ and the new line character.
Because the new line character is not interpreted, it is possible to create multi-line strings without using \n.

Interpolating strings with $

If a string is prefixed with a $ sign, special expressions that are embedded in curly braces ({…}) within the string are interpolated.
The format of such an interpolated string has three components: expression, alignment and format string:
$" … {expr}              … "
$" … {expr,align}        … "
$" … {expr:format}       … "
$" … {expr,align:format} … "
expression the required expression that produces a value that is to be embedded into the string
alignment an optional signed integer (literal or constant) that defines the minimum number of characters. If negative, the string is left aligned, if positive positiv aligned. If the expression is larger than the specified width, alignment is ignored. The alignment is prefixed with a comma (,)
format string an optional string expression whose semantics depend on the type of expression. The format string is prefixed by a colon (:)

Mixing @ and $

It is possible to have a verbatim string with interpolation by placing both @ and $ in front of the string: @$"…".

Example

using System;

class C {

   static void Main() {

      string txt = "Hello World";

      Console.WriteLine( " He said: \"Hello World\". ");

   //
   // Verbatim Strings (@"…")
   //
   //    Note: the @ sign can also be used to introduce a
   //    verbatim identifer (for (int @for in … ))
   //

      Console.WriteLine(@" He said: ""Hello World"". ");

      Console.WriteLine( " new\n line.");
      Console.WriteLine(@" new
 line.");
   // Console.WriteLine(@" He said \"Hello World\". ");


      Console.WriteLine( " > P:\\ath\\to\\directory");
      Console.WriteLine(@" > P:\ath\to\directory");

      Console.WriteLine( "He said, \"This is the last \u0063hance\x0021\"");
      Console.WriteLine(@"He said, ""This is the last \u0063hance\x0021""");


   //
   // Interpolated strings ($"…")
   //
      Console.WriteLine($" interpolated> He said: {txt}");

   //
   // Verbatim and interpolated
   //
      Console.WriteLine(@$"@$");

   }
}
Github repository about-C-Sharp, path: /language/types/reference/strings/verbatime-interpolated-etc.cs
This program prints
 He said: "Hello World".
 He said: "Hello World".
 new
 line.
 new
 line.
 > P:\ath\to\directory
 > P:\ath\to\directory
He said, "This is the last chance!"
He said, "This is the last \u0063hance\x0021"
 interpolated> He said: Hello World
@$

Links

.NET documentation:

Index