C# - TPL2141 logo C# - TPL2141

Special characters are used to modify the program element which they prefixed. C# supports the following special characters (Docs, 2017):

  1. @, the verbatim identifier character
  2. $, the interpolated string character

@, the verbatim identifier character

The verbatim character can be used to

  1. enable keywords to be used as identifiers
  2. indicate that a string is a “verbatim string literal”
    1. escape sequences are ignored
    2. can be used to define multiline string

1. enable keywords to be used as identifiers

This is illegal in C#:

string string = "this is a string";

But this is a valid syntax:

string @string = "this is a string";
Console.WriteLine(@string);

Live-code example

2. indicate that a string is a “verbatim string literal”

1.1 escape sequences are ignored
string normal = "first line \n second line";
string verbatim = @"first line \n second line";
Console.WriteLine(normal);
// --- output:
// first line 
//	second line

Console.WriteLine(verbatim);
// --- output:
// first line \n second line

which is commonly used for specifying file paths in Windows

// need to use '\' to escape the backslash character
string filename1 = "c:\\documents\\files\\u0066.txt";
// ignore escape sequences
string filename2 = @"c:\documents\files\u0066.txt";

Console.WriteLine(filename1);
// --- output:
// c:\documents\files\u0066.txt

Console.WriteLine(filename2);
// --- output:
// c:\documents\files\u0066.txt

Live-code example

1.2 can be used to define multiline string

string normal = "line1\nline2\nline3\n---";
string verbatim = @"line1
line2
line3
---";
Console.WriteLine(normal);
Console.WriteLine(verbatim);

Output:

line1
line2
line3
---
line1
line2
line3
---

Live-code example

$, the interpolated string character

Provide a more readable and convenient syntax to format strings (Docs, 2018).

Using this code snippet as an example:

double price = 12.456;
string name = "Lorem Ipsum";
DateTime paidOn = new DateTime(2018, 1, 1, 12, 34, 56);

Instead of doing this to join different variables together

// instead of doing this
string normal = name + " paid " + price.ToString("0.00") + " on " + paidOn.ToString("yyyy-MM-dd HH:mm:ss");

// Note: 00.00 -> numbers are formatted into 2 decimal places, padded with zeros

String interpolation is much simpler

// you can do this
string interpolated = $"{name} paid {price:0.00} on {paidOn:yyyy-MM-dd HH:mm:ss}";

Console.WriteLine(normal);
Console.WriteLine(interpolated);

Output:

Lorem Ipsum paid 12.46 on 2018-01-01 12:34:56
Lorem Ipsum paid 12.46 on 2018-01-01 12:34:56

Live-code example

References

  1. Docs, M. (2017, February 14). C# Special Characters. Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/
  2. Docs, M. (Ed.). (2018, March 26). string interpolation (C# Reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated