Using string literals in C#

In C#, string is the set of the characters enclosed by double quote. such as :

string str = "Welcome to Authorcode";

Welcome to Authorcode is the string here, you can print this string as:

string str = "Welcome to Authorcode";

Basically C# supports two forms of string literals: regular string literals and verbatim string literals. A regular string literal consists of zero or more characters enclosed in double quotes. Except this string can also contains some escape sequences such as single quote, double quote or backspace. Let’s say that we need to print Welcome to Authorcode in three lines like as :

simply we can use three Console.WriteLine statement:


Instead this we can use the ‘\n’ escape sequence. see the following:

Console.WriteLine("Welcome\n to \nAuthorcode");

Both above program will produce same outputs:

let’s take an another example- I want to insert double quote before and after Authorcode. such as :
Welcome to "Authorcode"

And write a simple statement like as:

Console.WriteLine("Welcome to "Authorcode"");

But the above statement will gives an error as : Invalid expression term ‘)’.
For it we should use another escape sequence \” like as:

 Console.WriteLine("Welcome to \"Authorcode\"");

there are the following escape sequences, you can use in C# string:

\a      aleret(bell)
\b      backspace
\f      form feed
\n      new line
\r      carriage return
\t      vertical tab
\v      horizantal tab
\0      null
\’       single quote
\”      double quote
\\       backslash

Additionally there is another thing you should know about Verbatim string literal. You can use Verbatim string literal begins with @ then no need to include some escape sequences. See the example:

 Console.WriteLine(@"Welcome to ""Authorcode"");