In C#, an escape sequence is a combination of characters that represents a special character or symbol and is used to insert such characters into a string or character literal. Escape sequences start with a backslash (\
) followed by a specific character or code.
Here are some commonly used escape sequences in C#:
\"
: Inserts a double quote character ("
).\'
: Inserts a single quote character ('
).\\
: Inserts a backslash character (\
).\n
: Inserts a new line character.\r
: Inserts a carriage return character.\t
: Inserts a tab character.\b
: Inserts a backspace character.\f
: Inserts a form feed character.\uXXXX
: Inserts a Unicode character represented by the hexadecimal valueXXXX
(e.g.,\u0041
represents the letter ‘A’).\xXX
: Inserts an ASCII character represented by the hexadecimal valueXX
(e.g.,\x41
represents the letter ‘A’).\0
: Inserts a null character.
Here’s an example that demonstrates the usage of escape sequences in C#:
string message = "Hello\tWorld!\nThis is a \"quoted\" string."; Console.WriteLine(message);
Output:
Hello World! This is a "quoted" string.
In the above example, the escape sequence \t
inserts a tab character, \n
inserts a new line, and \"
inserts a double quote character within the string.