Escape sequences are character combinations starting with a backslash () and followed by a letter or digits inserted in a string literal to produce a modified output. For example, to produce a newline when outputting a string, we can use the
You can see that once the compiler encounters the
character, it puts the cursor of the output to the next line and continue showing the output of the rest of the string. In fact, the WriteLine() method automatically adds
to the end of the string so:
is equivalent to:
The Write() method functions the same as the WriteLine() except that it doesn’t add a newline to the end f the string.
The following table shows a list of escape sequences and their corresponding effect:
|’||Single Quotation mark|
|”||Double quotation mark|
|u||Prints a Unicode character|
We used the when indicating the start of an escape sequence. Since the backslash gives special meaning to a string literal, we can print a backslash by using the \ escape sequence.
System.Console.WriteLine("We can print a \ by using the \\ escape sequence.");
We can print a by using the \ escape sequence.
The \ is also useful if you want to output, for example, a file path.
System.Console.WriteLine("C:\Program Files\Some Directory\SomeFile.txt");
C:Program FilesSome DirectorySomeFile.txt
Since we use the “ character to enclose a string, we can print a double quotation using the ” escape sequence.
System.Console.WriteLine("I said, "Programming is fun!".");
I said, “Programming is fun!”.
We can also use the ’ to print single quotation marks (‘).
System.Console.WriteLine("The dog's bone.");
The dog’s bone.
Tabs can be made by using the escape sequence.
escape sequence causes a carriage return which puts the cursor to the beginning of the current line. Once the cursor is at the beginning of the line, it overwrites any characters it encounters with those following the
On the example above, the letter K is after the
. When the
is encountered, the cursor is brought to the beginning of the line and K overwrites the letter M producing the new word.
To print any Unicode character, you can use the u escape sequence. To use the u, write the 4-digit hexadecimal value of the Unicode symbol right after the escape sequence. For example, if you want to print the copyright © symbol, you can use the u00A9 escape sequence since 00A9 is the hexadecimal value for the copyright symbol.
For a list of hexadecimal values for Unicode, go to the link below:
If the compiler finds an invalid escape sequence, an error will occur. One of the most common errors is when forgetting to use the \when a programmer wants to print a slash. As a result, the compiler interprets the very next letter following the .
The other escape sequences are rarely used and is therefore not discussed in this lesson.