C# Basics

Escape Sequences

The objective of this article is to familiarize you with the Escape Sequences and Verbatim Strings. You will learn different escape sequences with an easy to understand examples. Finally, Verbatim identifier with an at-sign (@) to use as an alternative to escape sequences.

C# string literals can include various unprintable control characters, such as tab, newline, or carriage-return. You cannot directly type these as a literal value instead escape sequences must be used. An escape sequence is represented by a backslash (\), followed by a specific character that has special meaning to the compiler. For example, “\n” represents a newline in a double-quoted string.

The following table shows some of the widely used escape sequences in C#.

Escape Sequence Meaning
\’ Output a Single quote.
\” Output a double quote.
\\ Output a Backslash.
\n Insert a newline.
\r Insert a carriage-return.
\t Insert a tab.
\0 Insert a null character.
\b Insert a backspace.

Escape Sequence Examples

To print a string that contains a newline, the escape character “\n” is used.

string strA = "Hello\nPirzada";
Console.WriteLine(strA);
OUTPUT

Hello
Pirzada

The following example demonstrates file path with the use of “\\” escape characters to escape backslashes “\”

string strA = "C:\\Codebuns\\file.cs";
Console.WriteLine(strA);
OUTPUT

C:\Codebuns\file.cs

If you want to embed quotes into the already quoted literal, you must use escape character backslash-quote (\”) to display them.

string strA = "I am a \"Senior .NET Developer\"."; 
Console.WriteLine(strA);
OUTPUT

I am a “Senior .NET Developer”.

Run Demo

C# Verbatim Strings – @

Try to embed all those double backslashes is annoying and hard to read. To avoid this problem, most developers use an alternate technique called verbatim string literals. You prefix a string literal with an at-sign (@) to create a verbatim string. Adding @ symbol before the string disables the support of escape sequences and a string is interpreted as is.

Verbatim String Examples

The following example demonstrates how @ symbol ignores escape characters and print out a string as is.

string strA = @"Hello\nPirzada";
Console.WriteLine(strA);
OUTPUT

Hello\nPirzada

Just use verbatim identifier to split a statement across multiple lines in the source code without the use of “\n” escape character.

string strA = @"Hello
Pirzada";
Console.WriteLine(strA);

The following example demonstrates file path without the use of “\\” escape characters.

string strA = @"C:\Codebuns\file.cs";
Console.WriteLine(strA);
OUTPUT

C:\Codebuns\file.cs

You can directly insert a double quote into a literal string just by doubling the quotes (“”). This will interpret as a single quotation mark ().

string strA = @"I am a ""Senior .NET Developer""."; 
Console.WriteLine(strA);
OUTPUT

I am a “Senior .NET Developer”.

Run Demo

Useful Articles

Sending
User Rating 0 (0 vote)

Add Comment

Click here to post a comment