C# Escape Characters

There are a few characters in computers that don’t have a printable symbol. This means they are non-printable.

For example:

  • White-space: Tab, backspace, newline, space.

  • Form feed

Also special symbols like single quotation and double quotation marks have specific purpose in the C# programming and so we can’t just add them as the actual value for a variable.

For example:

//WRONG
char character = ''';

Here the problem is that the compiler cannot figure out which single quotation mark should be considered as the beginning and which one as the end mark! For this reason we will get a compile time error.

Likewise the use of double quotation as the value of a variable of type String is not allowed.

//WRONG
String str = """;

When a compiler tries to compile this statement, it will get confused about where the first and last quotation marks are! And so it will stop compiling and returns error instead.

But the C# language brought an alternative to these characters which is called escape-sequence. They allow us to use these non-printable characters as well as special symbols like single and double quotation marks as the value for variables of type char and String in a program.

The effect of using these escape-sequence is exactly the same as if we’re using those especial characters.

Sequence Meaning
a Bell (alert)
b Backspace
f Form feed
n Newline
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash ()
Single quote (‘)
Double quote (“)
? Literal question mark
ooo ASCII character in octal notation
x hh ASCII character in hexadecimal notation

Example:


char character = ''';

Now because we used the escape-sequence of the single-quotation mark, the character variable can store the single-quotation mark and the compiler will not complain about this statement any more.

Another example:

using System;

namespace quickExample

{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("tt" + " John Doe");
}
}
}

Output:

John Doe

In this example we’ve added two tabs via t escape sequence to the message that we sent to the output stream.

Another example:

using System;

namespace quickExample

{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("aaaa");
}
}
}

Output:

If the device that you’re running this program on has bell (alert), you’ll hear 4 beep sounds in a row.